tkinter 按钮通过一个循环,我如何识别哪个被点击?

问题描述

我创建了一个循环来为列表中的每个元素创建一个按钮。我如何确定点击了哪个按钮,然后为每个按钮分配一个命令,这将创建一个与点击的按钮同名的新页面?。

       yvalue = 200
    for i in sdecks:
        deckbutton1=Button(fcpage,text=i,width=21,bd=2,fg="ghost white",bg="orchid1")
        deckbutton1.place(x=105,y=yvalue)
        yvalue = yvalue + 20

解决方法

要么我没问你问题,要么这个(改编自 here)应该回答你的问题:

from functools import partial
import tkinter as tk


def create_new_page(name_of_page):
    print("Creating new page with name=\"%s\"" % name_of_page)


root = tk.Tk()

for i in range(5):
    # Create the command using partial
    command = partial(create_new_page,i)

    button = tk.Button(root,text="Button number"+str(i+1),command=command)
    button.pack()

root.mainloop()