初始代码:
import turtle as t
#创建窗口
game = t.Screen()
game.bgcolor('black')
game.setup(800,600) #宽、高
pen = t.Turtle()
pen.color('white')
pen.write('hello',align='left',font = ('Arial',20,'bold'))
#主循环
while True:
x = pen.xcor()
y = pen.ycor()
pen.clear()
运行效果:
点击右上角的×关闭窗口后,出现如下错误:
改后的代码如下:
import turtle as t
#创建窗口
game = t.Screen()
game.bgcolor('black')
game.setup(800,600) #宽、高
pen = t.Turtle()
pen.color('white')
pen.write('hello',align='left',font = ('Arial',20,'bold'))
#添加的部分 begin
#判断是否要退出
running = True
def stop_loop():
global running
running = False
#获取窗口的Tk对象,并注册关闭事件
root = game.getcanvas().winfo_toplevel()
root.protocol('WM_DELETE_WINDOW',stop_loop)
#end
#主循环
while running: #此处将True换为running
x = pen.xcor()
y = pen.ycor()
pen.clear()
关闭窗口后无错误,如下图: