想在 tkinter 裡動態產生多個按鈕,但如下使用下面的 code, 完全無事件,command 在被產生時,就執行完了。
下面這篇是「錯誤答案」:
https://stackoverflow.com/questions/57554418/get-the-index-of-a-button-while-pressing-which-is-in-an-array
you can pass argument to the function you use as command.
example:
def myButttonCommand(index):
print("this is the "+index+"th' button")
buttons = []
for i in range (0,10):
buttons[i] = tk.Button(command=myButtonCommand(i))
Question: assign an Array element to a tkinter button via for each loop?
If you want to get the Button['text']
on click, use .bind(<Button-1>...
instead of command=
:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
for r in range(1, 8):
for c in range(1, 5):
btn = tk.Button(self, text=chr((r*4)+c+60),
height='1', width='1',
bg='white', fg='deep sky blue', font=("Helvetica", 18))
btn.grid(row=r,column=c)
btn.bind('<Button-1>', self.listitems)
def listitems(self, event):
print(event.widget['text'])
if __name__ == "__main__":
App().mainloop()