python - 为什么当鼠标悬停在另一个按钮上时,会调用 tkinter 中绑定到一个按钮的函数?
问题描述
我试图了解我的代码中发生了什么。应用程序按钮和键盘按钮(回车和小键盘回车)绑定了一项功能。我注意到它对我来说很奇怪。当我单击任何其他按钮(不是分配给它的按钮)然后将鼠标移到下一个按钮上时,它会循环运行。我无法发现我所做的错误。请问你能帮帮我吗?这是我的代码:
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()
解决方案
推荐阅读
- quarkus - 当 application-type=service 时如何在 Quarkus 应用程序中使用 @IdToken?
- node.js - 自动增量从 x 开始
- android - Android 中的消息应用程序无需用户交互即可触发 GET 链接
- machine-learning - k折交叉验证中较大或较小k的权衡
- c++ - CMake:“导入的目标
包括不存在的路径” - reactjs - Office Fluent UI / DatePicker - onSelectDate 不发送事件作为参数
- javascript - 从数据中删除叶节点
- javascript - 添加chart.js后,我的锚标签在我的网站中不起作用
- android - 云数据库 AGConnectInitializeProvider 错误
- node.js - Facebook API,创建创意错误无法加载帖子