繁体   English   中英

如何在tkinter python中使按钮的背景颜色闪烁

[英]How to make background color of button flashing in tkinter python

我有一个简单的 window 有 2 个按钮和一个条目。 如果条目中的文本与 button2 上的文本相同,我想让 button2 闪烁(闪烁)。 尝试在 function 之后使用,但没有运气。 我可以改变颜色,但不知道如何让它闪烁。 这是我的代码:

import tkinter as tk

text = ""
def gettext():
    text = entry.get()
    if text == button2['text']:
        button2.config(background='red')
        
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
button1 = tk.Button(root, text="Text", command=gettext)
button1.pack(side="bottom", padx=20, pady=20)
button2 = tk.Button(root, text="Flashing")
button2.pack(side="bottom", padx=20, pady=20)
root.mainloop()

尝试这个:

import tkinter as tk

text = ""
def gettext(*args):
    text = entry.get()
    if text == button2.cget("text"):
        # Change the button's bg to red
        button2.config(background="red")
        # After 100ms reset the variable's bg
        button2.after(100, lambda: button2.config(background="#f0f0ed"))
        # After 100 more milliseconds call `gettext` again
        button2.after(200, gettext)

root = tk.Tk()
# Create a StringVar variable
variable = tk.StringVar(root)
# Trace the variable
variable.trace("w", gettext)
# Attach it to the entry
entry = tk.Entry(root, textvariable=variable)
entry.pack()
button2 = tk.Button(root, text="Flashing")
button2.pack()
root.mainloop()

我删除了其中一个按钮并添加了一个StringVar (以便于测试)。 逻辑很简单:

  • 将按钮的背景更改为红色
  • 等待 100 毫秒,重置按钮的 bg
  • 再过 100 毫秒后,再次运行 function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM