首页 > 解决方案 > 为什么当鼠标悬停在另一个按钮上时,会调用 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()

标签: pythonbuttontkinter

解决方案


<Enter>表示鼠标悬停(鼠标进入)。
<Leave>表示鼠标悬停(鼠标离开)。

如果要绑定密钥Enter,则必须使用<Return>而不是<Enter>


您可以在 effbot.org 上找到一些键的符号:事件和绑定

您可以在 Tcl/Tk 文档中找到其他键:keysyms


推荐阅读