我试图了解我的代码中发生了什么。有一项功能绑定(bind)到应用程序按钮和键盘按钮(Enter 和数字键盘 Enter)。我注意到它的行为对我来说很奇怪。当我单击任何其他按钮(不是分配给它的按钮)然后将鼠标移到下一个按钮上时,它会循环运行。我无法发现我所做的错误。请问你能帮帮我吗?这是我的代码:
import tkinter as tk
import tkinter.ttk as ttk
class Gui(tk.Tk):
def __init__(self):
super().__init__()
self.user_input = tk.StringVar()
tk.Label(self, textvariable=self.user_input).grid()
buttons = self.create_buttons()
for x in buttons: x.grid()
def write(self, *_, button=None):
current = self.user_input.get()
if button:
if len(current)<4:
current += button
else:
current = current[:-1]
self.user_input.set(current)
def apply(self, *_):
print(self.user_input.get())
def create_buttons(self):
buttons = []
for x in range(10):
func = lambda *_, x=x: self.write(button=str(x))
buttons.append(ttk.Button(self, text=x, command=func))
self.bind(str(x), func)
buttons.append(ttk.Button(self, text="Ok", command=self.apply))
self.bind("<Enter>", self.apply)
self.bind("<KP_Enter>", self.apply)
buttons.append(ttk.Button(self, text="<-", command=self.write))
self.bind("<BackSpace>", self.write)
return buttons
app = Gui()
app.mainloop()
最佳答案
<Enter>
表示鼠标悬停(鼠标输入)。
<Leave>
表示鼠标悬停(鼠标离开)。
如果要绑定(bind) key Enter
那么你必须使用<Return>
而不是<Enter>
您可以在 effbot.org 上找到一些按键的符号:Events and Bindings
您可以在 Tcl/Tk 文档中找到其他键:keysyms
关于python - 为什么当鼠标悬停在另一个按钮上时,会调用 tkinter 中绑定(bind)到一个按钮的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996413/