Tkinter绑定返回/输入按钮

时间:2016-07-27 07:52:19

标签: python-2.7 tkinter

我有一个按钮,用于计算您点击它的次数。我想使用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()

请建议如何以最简单的方式实现此目的

1 个答案:

答案 0 :(得分:1)

好的,感谢@BryanOakley的评论。正确答案是:

1 - >一方面,您可以使用button方法设置所有事件(windowbind对象),它将是:

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