我有一个按钮,用于计算您点击它的次数。我想使用return / enter键也可以。这是我的代码
import Tkinter
window=Tkinter.Tk()
window.title("Clicks Counter")
presses=0
def addClick(self):
global presses
presses += 1
lbl.configure(text=presses)
lbl=Tkinter.Label(window, text=presses)
lbl.pack()
btn=Tkinter.Button(window, text="Click Me", command=addClick)
btn.config(font=('helvetic',40))
btn.pack(expand=True, fill='both')
window.mainloop()
请建议如何以最简单的方式实现此目的
答案 0 :(得分:1)
好的,感谢@BryanOakley的评论。正确答案是:
1 - >一方面,您可以使用button
方法设置所有事件(window
为bind
对象),它将是:
window.bind('<Return>', addClick)
window.bind('<BackSpace>', addClick)
btn.bind('<Button-1>', addClick)
addClick
方法将是:
def addClick(event):
global presses
presses += 1
lbl.configure(text=presses)
第一个选项代码:
import Tkinter
window=Tkinter.Tk()
window.title("Clicks Counter")
presses=0
def addClick(event): # Change this line!
global presses
presses += 1
lbl.configure(text=presses)
window.bind('<Return>', addClick) # Change this line!
window.bind('<BackSpace>', addClick) # Change this line!
lbl=Tkinter.Label(window, text=presses)
lbl.pack()
btn=Tkinter.Button(window, text="Click Me")
btn.config(font=('helvetic',40))
btn.pack(expand=True, fill='both')
btn.bind('<Button-1>', addClick) # Change this line!
window.mainloop()
2 - &gt;另一方面,您可以更改addClick
方法,添加可选参数作为@BryanOakley注释。然后,您不会更改command
的第三个参数(Tkinter.Button()
)。它将是:
def addClick(event=None):
global presses
presses += 1
lbl.configure(text=presses)
window.bind('<Return>', addClick)
window.bind('<BackSpace>', addClick)
第二个选项代码:
import Tkinter
window=Tkinter.Tk()
window.title("Clicks Counter")
presses=0
def addClick(event=None): # Change this line!
global presses
presses += 1
lbl.configure(text=presses)
window.bind('<Return>', addClick) # Change this line!
window.bind('<BackSpace>', addClick) # Change this line!
lbl=Tkinter.Label(window, text=presses)
lbl.pack()
btn=Tkinter.Button(window, text="Click Me", command=addClick)
btn.config(font=('helvetic',40))
btn.pack(expand=True, fill='both')
window.mainloop()
我希望这是你想要的,再次感谢@BryanOakley:D