python - 为什么当鼠标悬停在另一个按钮上时,会调用 tkinter 中绑定(bind)到一个按钮的函数?

标签 python button tkinter

我试图了解我的代码中发生了什么。有一项功能绑定(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/

相关文章:

python - 单个选项卡中的多个框架 ttk.Notebook

python - PyQt - 将 QAction 连接到函数

python - 尝试让 python RegEx 删除括号 [ abc ] 之间的所有内容

python - 如何利用所有核心来加速基于numpy 3D数组的仿真程序?

java - 在我的第一个 GUI java 应用程序中使用 .add() 方法向布局添加按钮

python - 当我调用 update_idletasks() 时,Tkinter 有时会卡住

python - 在 Linux 上使用 Python 对平板电脑施加压力

ios - iphone plus中的Swift奇怪的后退按钮文本

css - 如何仅创建此按钮形状 CSS?

python - 无法调用按钮命令 : application has been destroyed