我正在使用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()
答案 0 :(得分:2)
您可以使用生成器和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()
的组合来完成任务:
nav
答案 1 :(得分:0)
为了进一步澄清abccd的答案,您的代码的问题在于使用
time.sleep()
vs Tk after()
。
在您的示例中,sleep()
将冻结程序执行。 Tk没有时间在睡眠调用之间重新绘制窗口,因此您可以有效地看到sleep()
命令的无限循环。因此冻结/崩溃。
after()
将按您需要的方式安排您的Tk应用程序。
答案 2 :(得分:-1)
早期,为了避免使用Tk出现奇怪错误,我在一个线程中创建了所有UI元素并启动了等待传入事件的循环。来自其他线程的所有交互元素或活动都将“查询”/事件放入此队列,但是元素的实际更改发生在创建元素的线程中。这是Tcl / Tk(8.5,8.6)的规则。尝试这样的模型。请看这段代码是如何完成的 - https://code.google.com/archive/p/pybase/downloads