我试图了解我的代码中发生了什么。有一个功能绑定到应用程序按钮和键盘按钮(回车和小键盘回车(。我注意到它对我来说表现得很奇怪。当我单击任何其他按钮(不是分配给它(然后将鼠标移到下一个按钮上时,它会循环运行。我无法发现我所做的错误。你能帮我吗?这是我的代码:
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>
表示鼠标悬停(鼠标离开(。
如果要绑定密钥Enter
则必须使用<Return>
而不是<Enter>
您可以在 effbot.org 上找到的某些键的符号:事件和绑定
您可以在 Tcl/Tk 文档中找到的其他键:键符号