tkinter.按钮退出事件处理后保留凹陷的外观

2024-04-26 07:17:22 发布

您现在位置:Python中文网/ 问答频道 /正文

再试一次…我有一个Python编程的GUI,在这个GUI中,按下的按钮在事件处理程序退出后保留一个按下的外观。事件处理程序使用了messagebox。通常,这种情况不会发生。下面是一个重现问题的示例:

import tkinter as tk
from tkinter import messagebox

# post a message
def post_message(event):
    messagebox.showinfo("Sample Messgebox", "close this and look at button")

root = tk.Tk()
b = tk.Button(root, text="Press Me")
b.bind("<Button-1>", func=post_message)
b.pack()
root.mainloop()

Tags: import处理程序messagetkinter编程事件情况gui
2条回答

虽然我不知道为什么你的代码不能正常工作,但因为我对Py还比较陌生,所以我设法重写了它,使之只需很少的修改。你知道吗

解决方案1

import tkinter as tk
from tkinter import messagebox

# post a message
def post_message():
    messagebox.showinfo("Sample Messgebox", "close this and look at button")

root = tk.Tk()
b = tk.Button(root, text="Press Me", command=post_message)
b.pack()
root.mainloop()

我改变了什么:

不再是bind()因为这导致了问题,而是通过在声明Button对象时添加command=选项来调用函数

另外请注意,command选项不提供用event参数调用的函数,因此必须将其删除,否则会出现错误。你知道吗

另一种解决方法,这次它可以与bind()一起使用,非常好!你知道吗

解决方案2

import tkinter as tk
from tkinter import messagebox

# post a message
def post_message(event):
    root.after(0, lambda: messagebox.showinfo\
    ("Sample Messgebox", "close this and look at button"))

root = tk.Tk()
b = tk.Button(root, text="Press Me")
b.bind("<Button-1>", post_message)
b.pack()
root.mainloop()

我用master.after(time_in_ms, callback_func)告诉程序应该在给定的时间后运行给定的func,这里是0毫秒,所以尽快。你知道吗

为什么兰巴在里面?Lambda是一个动态的、未命名的函数。After引用要调用的函数,因此不能直接为其指定参数。你知道吗

为此,如本例中所示,设置一个将被引用的lambda。你知道吗

当它最终被调用时,lambda func将调用您想要调用的实际函数,并给出它所需的参数。你知道吗

如果您还不知道lambdas是如何工作的,我知道您现在很困惑,请在这里阅读更多关于它们的内容,它们非常有用:Lambdas explained

有关tkinter的重要信息来源,请访问effbot.org Events and Bindings

当您将blind与事件Button-1一起使用时,您没有使用按钮的主事件。可以使用参数command激活按钮的主事件。你知道吗

import tkinter as tk
from tkinter import messagebox

def post_message():
    messagebox.showinfo("Sample Messgebox", "close this and look at button")

root = tk.Tk()
b = tk.Button(root, text="Press Me", command=post_message)
b.pack()
root.mainloop()

相关问题 更多 >