1

我一直在尝试在 Python Turtle 中制作一个绘图程序,但由于某种原因它无法正常工作。我正在使用 pen() 工具,我的代码如下所示

from turtle import *
import random

pen()
bgcolor('black')
pencolor('white')
pen.ondrag(pen.goto)
listen()
mainloop()

我看过这个http://docs.python.org/2/library/turtle.html,它说要输入turtle.ondrag(turtle.goto),但因为我使用的是笔,所以它应该像笔一样工作。 ondrag 但它没有,所以有人可以解决这个问题。

谢谢果冻矿工

4

3 回答 3

0
from turtle import *
ts = Screen()
ondrag(goto)
shapesize(10)
pensize(40)
speed(0)
mainloop()

我认为这肯定会奏效。

您可以更改大小和其他内容在这里您使用的是默认海龟。

抱歉,您需要注意缩进

于 2020-01-05T12:39:38.780 回答
0

First, pen() is not the function you want. Second, although Pen is a synonym for Turtle, pen is not a synonym for turtle. Here's how to go about using ondrag() if you'd like to use Pen instead of Turtle:

from turtle import Pen, Screen, mainloop

def ondrag_handler(x, y):
    pen.ondrag(None)  # disable handler inside handler

    pen.setheading(pen.towards(x, y))  # turn toward cursor
    pen.goto(x, y)  # move toward cursor

    pen.ondrag(ondrag_handler)

screen = Screen()
screen.bgcolor('black')

pen = Pen()
pen.color('white')
pen.shapesize(2)  # make it larger so it's easier to drag

pen.ondrag(ondrag_handler)

screen.listen()
mainloop()  # screen.mainloop() preferred but not in Python 2

The turtle.ondrag(turtle.goto) makes for a nice short example in the documentation but in reality isn't practical. You want to disable the event handler while handling the event otherwise the events stack up against you. And it's nice to turn the mouse towards your cursor as you drag it.

于 2018-01-23T07:07:37.507 回答
0

我将简化和澄清提问者给出的代码:

from turtle import *

ts = Screen(); tu = Turtle()
ts.listen()
ondrag(tu.goto)
mainloop()

这行得通。您必须单击乌龟并拖动它。

于 2018-01-22T08:19:22.797 回答