python - 如何不断改变背景颜色?

标签 python python-2.7 tkinter

我正在使用 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/

相关文章:

python - Tkinter 窗口不显示任何内容

python - 如何在 python 中删除字符串前后的字符?

python - 从另一个列表中删除列表列表

python - 如何在没有任何顺序的情况下更新我的数据库对象?

Pythonunittest : setUpClass(), 未调用tearDownClass()、setUpModule() 和tearDownModule()

python: langton's ant pygame 第一步问题

Python - 如何使用单个函数来获取有关 Tkinter 中框架的信息

python - 加密——怎么做

python - 用于锯齿状切片的 numpy 速记

python - 打印 Webkit 报告报错