1 回答
TA贡献1797条经验 获得超4个赞
在事件驱动的环境中,我们不能简单地做while True:并期望事情有效。这样做有效地阻止了一些事件的触发。窗口关闭事件可能很棘手——比乌龟有时能够处理的更棘手,所以我们可能需要下降到 tkinter 级别才能正确执行。
下面是我重新编写的代码,以使用计时器事件替换无限循环,并使用窗口关闭处理程序来捕获窗口关闭事件。处理程序尝试干净地停止您的内部循环和计时器事件,然后完成关闭窗口。加上一些其他的风格变化:
from turtle import Screen
from random import randint
from os import system
screen = Screen()
screen.colormode(255)
screen.bgcolor(0, 0, 0)
curR = 0
curG = 0
curB = 0
running = True
def window_closing():
global running
running = False
screen.ontimer(screen.bye, 500)
def switch_color_target():
global curR, curG, curB
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
success = False
RD = False
GD = False
BD = False
while running and not success:
if curR < r:
curR += 1
elif curR > r:
curR -= 1
else:
RD = True
if curG < g:
curG += 1
elif curG > g:
curG -= 1
else:
GD = True
if curB < b:
curB += 1
elif curB > b:
curB -= 1
else:
BD = True
screen.bgcolor(curR, curG, curB)
system("cls")
print(r)
print(g)
print(b)
success = RD and GD and BD
if success:
print("R")
print("B")
print("G")
else:
print(curR)
print(curG)
print(curB)
if running:
screen.ontimer(switch_color_target, 250)
switch_color_target()
canvas = screen.getcanvas()
root = canvas.winfo_toplevel()
root.protocol("WM_DELETE_WINDOW", window_closing)
screen.mainloop()
我和你使用的操作系统不同,所以我不能彻底测试这个——试一试看看它是否能解决你的问题。
添加回答
举报