尝试运行此代码时,出现
的关键错误KeyError: <tkinter.Button object .!button4>
所有按钮1-5的按钮编号不同。
我不明白它是什么意思,因为我以为我指的是正确的按钮。请帮忙!这是我的代码:
import tkinter as tk
def button_click(event = None):
which_button = event.widget
var = f[which_button]
if var in f:
var.set(f[var])
else:
for i, j in enumerate(v):
if j == v[i]:
var.set(k[i])
window = tk.Tk()
window.title("Flashcards")
k=[]
v=[]
f={"Bonjour": "Hello",
"Lundi": "Monday",
"Parler": "To Talk",
"Manger": "To Eat",
"Dormir": "To Sleep"}
for key,val in f.items():
k.append(key)
v.append(val)
for i in range(5):
s = tk.StringVar()
s.set(k[i])
b = tk.Button(window, textvariable = s, width = 10)
b.bind("<Button-1>", button_click)
b.grid(row = 0, column = i)
window.mainloop()
答案 0 :(得分:0)
迟到的回答,但是:为什么在Button有回调函数时使用bind?使用partial()
,您可以为每个按钮指定一个特定的回调。
import tkinter as tk
from functools import partial
def button_click(event=None, key=None):
print(key, '-', f[key])
window = tk.Tk()
window.title("Flashcards")
f={"Bonjour":"Hello","Lundi":"Monday","Parler":"To Talk",
"Manger":"To Eat","Dormir":"To Sleep"}
for i,key in enumerate(f.keys()):
b = tk.Button(window, text=key, width = 10)
b.bind("<Button-1>", partial(button_click, key=key))
b.grid(row = 0, column = i)
window.mainloop()
如果您不熟悉partial
,则它与lambda:
类似,但语法不同。