如何改变tkinter按钮在线几秒钟


def click():
button1.configure(bg="gray")
time.sleep(1)
button1.configure(bg="green")
button1 = Button(win, text="Button",bg="green",activebackground="red")
button1.pack()

我试图将按钮更改为灰色仅一秒钟,然后更改回绿色。但是它不会变成灰色

您需要在打包后绑定该事件

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()

顺便说一句,关于这个主题的可靠资源,有点过时,但作为一种教育材料-写得很好-短:Dhttp://thinkingtkinter.sourceforge.net/

你必须这样做。如果你使用Time库,软件将无法工作或者你可以在Python中使用Threading模块来实现多线程,但是这个方法有点复杂

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()

第一个click()从未执行过。其次,所有更新都由tkintermainloop()处理,因此这些更改将在功能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()

最新更新