简体   繁体   English

尝试在python中拖动乌龟时内核崩溃

[英]Kernel crashes when trying to drag a turtle in python

I decided to use the built-in turtle for the display of my whole program, but if there's a better option you can leave it here too. 我决定使用内置的Turtle来显示整个程序,但是如果有更好的选择,您也可以将其保留在此处。

So, when I was using the turtle and bound a function to the left click drag, it ends up working fine, but only for slow mouse velocities and, thus, for short amounts of time before crashing my kernel and giving me a fatal "stack overflow" error. 因此,当我使用乌龟并将函数绑定到左键单击拖动时,它最终可以正常工作,但仅适用于缓慢的鼠标速度,因此,在崩溃内核并给我致命的“堆栈”之前需要很短的时间溢出”错误。

Code: 码:

from turtle import *
screen = Screen()
t1 = Turtle()
t1.shape("circle")
t1.pu()
bi = 1
ni = 1
screen.tracer(None, 0)
t1.speed(0)
screen.screensize(1000,1000)
def grow(ke):
    t1.goto(ke.x - 475,-ke.y + 400)
    global bi, ni
    t1.shapesize(bi,ni)
    bi += .004
    ni += .004
s2 = getcanvas()
s2.bind("<B1-Motion>", grow)
s2.bind("<Button-1>", grow)

There are several issues with your code: 您的代码有几个问题:

  • You didn't disable events inside the event hander, which is what lead to your fatal "stack overflow" error. 您没有在事件处理程序内部禁用事件,这是导致致命的“堆栈溢出”错误的原因。

  • You bypassed turtle's own event mechanism and used that of the tkinter underpinning. 您绕过了乌龟自身的事件机制,并使用了tkinter的基础机制。 Sometimes that's necessary, but it's not the place to start. 有时这是必要的,但这不是开始的地方。

  • You don't need to turn off tracer() as you're not drawing anything. 由于不需要绘制任何内容,因此无需关闭tracer()

Below is my rework of your code that I believe achieves your basic goals. 以下是我对您的代码的重做,相信可以实现您的基本目标。 You can drag the turtle around the screen cleanly and it will grow as you do. 您可以将乌龟干净地拖到屏幕周围,并且会随着您的成长而增长。 You can click anywhere on the screen and the turtle will come to you and grow: 您可以单击屏幕上的任意位置,然后乌龟就会出现并生长:

from turtle import Turtle, Screen

def grow(x, y):
    global bi, ni

    turtle.ondrag(None)  # disable events when inside handler
    screen.onclick(None)

    turtle.goto(x, y)
    turtle.shapesize(bi, ni)

    bi += 0.04
    ni += 0.04

    turtle.ondrag(grow)
    screen.onclick(grow)

screen = Screen()
screen.screensize(1000, 1000)

turtle = Turtle('circle')
turtle.speed('fastest')
turtle.penup()

bi = ni = 1

turtle.ondrag(grow)
screen.onclick(grow)

screen.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM