I have created a list and made it so each item in the list creates a button called that item. I need to identify which button has been clicked but can't seem to find a way can anyone help. thanks
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()
CodePudding user response:
There are many ways to achive what you want.
Approach 1 using event:
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
Approach 2 using lambda to store predefined arguments:
CPU = tk.Button(newWindow, text = CPUBUT, pady = 10, width = 12,command=lambda info=CPUBUT:buttonClick(info))
Approach 3, using a dictonary:
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()
CodePudding user response:
The quickest and the easiest way would be to use the lambda function with the pressed button information already supplied. I also applied optimizations no need to use range or n variable you were using
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()