def click():
button1.configure(bg="gray")
time.sleep(1)
button1.configure(bg="green")
button1 = Button(win, text="Button",bg="green",activebackground="red")
button1.pack()
我嘗試將按鈕更改為灰色,而不是更改回綠色。但它不會變成灰色
uj5u.com熱心網友回復:
您需要在打包后系結該事件
from tkinter import *
import time
def click(event):
if button1["background"] == "green":
time.sleep(3)
button1["background"] = "yellow"
else:
button1["background"] = "green"
root = Tk()
myContainer1 = Frame(root)
myContainer1.pack()
button1 = Button(myContainer1, text="Button", bg="green")
button1.pack()
button1.bind("<Button-1>", click) # binding event here
root.mainloop()
順便說一句,關于該主題的可靠資源,有點過時但作為教育材料 - 寫得很好 - 簡短:D http://thinkingtkinter.sourceforge.net/
uj5u.com熱心網友回復:
你必須這樣做。如果使用 Time 庫,軟體將無法作業,或者您可以使用 Threading 模塊在 Python 中進行多執行緒處理,但是這種方法有點復雜
from tkinter import *
def click(event):
def loop(i):
if i==1:
button1.configure(bg="gray")
elif i==2:
button1.configure(bg="red")
return
i=i 1
button1.after (1000, lambda : loop (i))
loop (1)
root = Tk()
myContainer1 = Frame(root)
myContainer1.pack()
button1 = Button(myContainer1, text="Button", bg="red")
button1.pack()
button1.bind("<Button-1>", click) # binding event here
root.mainloop()
uj5u.com熱心網友回復:
首先click()從未被執行過。其次,所有更新都由 tkinter 處理mainloop(),因此這些更改將在函式click()退出后處理,并且只會看到最后一次更改。
您可以使用.after()而不是sleep()在一秒鐘后將按鈕的顏色更改回綠色:
def click():
button1.configure(bg="gray")
# change the background color back to green after 1 second
button1.after(1000, lambda: button1.configure(bg="green"))
button1 = Button(win, text="Button", bg="green", activebackground="red", command=click)
button1.pack()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/483345.html
下一篇:tkinter畫布上的鉛筆畫
