Tkinter 按钮识别

Tkinter button identification

我创建并制作了一个列表,因此列表中的每个项目都会创建一个名为该项目的按钮。我需要确定单击了哪个按钮,但似乎找不到任何人都可以提供帮助的方法。谢谢

import tkinter as tk

window = tk.Tk()
window.title("PC CONFIGURATOR")
window.geometry("1280x720")

def createNewWindowCPU():
    newWindow = tk.Toplevel(window)
    newWindow.geometry("1280x720")
    newWindow.title("CPU")
    AMD = tk.Button(newWindow, text = "AMD", pady = 10, width = 12, command=createNewWindowAMD)
    AMD.pack()

def createNewWindowAMD():
    newWindow = tk.Toplevel(window)
    newWindow.geometry("1280x720")
    newWindow.title("AMD")
    n = -1
    c = -1
    CPUF = ["Ryzen 9 5900x", "Ryzen 7 5800x", "Ryzen 5 5600x", "Ryzen 9 3900x", "Ryzen 7 3700x", "Ryzen 5 3600x"]
    def buttonClick():
        print(CPUBUT)
    for i in range(len(CPUF)):
        n = n + 1
        print(CPUF[n])
        CPUBUT = CPUF[n]
        CPU = tk.Button(newWindow, text = CPUBUT, pady = 10, width = 12, command = buttonClick)
        CPU.pack()

CPU = tk.Button(window,text = "CPU", pady = 10, width = 12, command=createNewWindowCPU)
CPU.pack()

window.mainloop()

有很多方法可以实现您想要的。

方法 1 使用事件:

def buttonClick(event):
    button = event.widget#use event info
    print(button['text'])#cget text

CPU = tk.Button(newWindow, text = CPUBUT, pady = 10, width = 12)#delete command option
CPU.bind('<Button-1>',lambda e:buttonClick(e))#bind click event

使用 lambda 存储预定义参数的方法 2:

CPU = tk.Button(newWindow, text = CPUBUT, pady = 10, width = 12,command=lambda info=CPUBUT:buttonClick(info))

方法 3,使用字典:

def button_1_cmd():
    print(1)
(...)
CPUF = {"Ryzen 9 5900x":button_1_cmd,
            "Ryzen 7 5800x":button_2_cmd,
            "Ryzen 5 5600x":button_3_cmd,
            "Ryzen 9 3900x":button_4_cmd,
            "Ryzen 7 3700x":button_5_cmd,
            "Ryzen 5 3600x":button_6_cmd}
    
    for key,value in CPUF.items():
        b = tk.Button(newWindow,text = key,command=value)
        b.pack()

最快和最简单的方法是使用 lambda 函数和已提供的按下按钮信息。 我还应用了优化,无需使用您正在使用的范围或 n 变量

def createNewWindowAMD():
    newWindow = tk.Toplevel(window)
    newWindow.geometry("1280x720")
    newWindow.title("AMD")

    CPUF = ["Ryzen 9 5900x", "Ryzen 7 5800x", "Ryzen 5 5600x", "Ryzen 9 3900x", "Ryzen 7 3700x", "Ryzen 5 3600x"]
    
    def buttonClick(text):
        print('You clicked on ', text)
        
    for CPUBUT in CPUF:
        CPU = tk.Button(newWindow, text = CPUBUT, pady = 10, width = 12, command = lambda text=CPUBUT:buttonClick(text))
        CPU.pack()