我正在使用 Tkinter 开发一个循环,并且想知道如何更改代码以便我可以每秒更改背景。在这段代码中应该可以工作,但是每当我运行该程序时它就会崩溃!
我已经请了专业人士来查看它,但我们仍然无法弄清楚为什么这段代码不起作用。此外,当您删除 while True:
部分时,它只会将背景配置为最后一种颜色。
from Tkinter import *
import time
root = Tk()
root.geometry("500x500+200+200")
root.title("Epilepsy Giver")
root.resizable(width = FALSE, height = FALSE)
def wait():
time.sleep(1)
def start():
while True:
wait()
root.configure(background='red')
wait()
root.configure(background='orange')
wait()
root.configure(background='yellow')
wait()
root.configure(background='green')
wait()
root.configure(background='blue')
wait()
root.configure(background='purple')
wait()
root.configure(background='violet')
startButton = Button(root,text="START",command=start)
startButton.pack()
root.mainloop()
最佳答案
您可以结合使用生成器和 root.after()
来完成您的任务:
from Tkinter import *
root = Tk()
root.geometry("500x500+200+200")
root.title("Epilepsy Giver")
root.resizable(width = FALSE, height = FALSE)
def get_colour():
colours = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'violet']
while True:
for c in colours:
yield c
def start():
root.configure(background=next(colour_getter)) # set the colour to the next colour generated
root.after(1000, start) # run this function again after 1000ms
colour_getter = get_colour()
startButton = Button(root,text="START",command=start)
startButton.pack()
root.mainloop()
关于python - 如何不断改变背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43721055/