1 回答

TA貢獻(xiàn)1797條經(jīng)驗 獲得超4個贊
在事件驅(qū)動的環(huán)境中,我們不能簡單地做while True:并期望事情有效。這樣做有效地阻止了一些事件的觸發(fā)。窗口關(guān)閉事件可能很棘手——比烏龜有時能夠處理的更棘手,所以我們可能需要下降到 tkinter 級別才能正確執(zhí)行。
下面是我重新編寫的代碼,以使用計時器事件替換無限循環(huán),并使用窗口關(guān)閉處理程序來捕獲窗口關(guān)閉事件。處理程序嘗試干凈地停止您的內(nèi)部循環(huán)和計時器事件,然后完成關(guān)閉窗口。加上一些其他的風(fēng)格變化:
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()
我和你使用的操作系統(tǒng)不同,所以我不能徹底測試這個——試一試看看它是否能解決你的問題。
添加回答
舉報