簡體   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