如何移动绿色字符以在python中使用onkey?

时间:2019-05-24 14:53:18

标签: python turtle-graphics

我想左右移动此绿色字符以使用键盘。

但是,下面的代码显示图片静止不动并分别移动。这是我的代码:

import turtle

A = turtle.Turtle()
A.speed(0)
A.hideturtle()
screen = turtle.Screen()

def MyGoto(A,x_xx,x_yy):
 A.penup()
 A.goto(x_xx,x_yy)
 A.pendown()

def DrawCircle(A,x_xx, x_yy, x_radius, x_color):
 MyGoto(A,x_xx,x_yy)
 A.color(x_color)
 A.fillcolor(x_color)
 A.begin_fill()
 A.circle(x_radius)
 A.end_fill()

global_xx = 10
def left():
 global global_xx
 turtle.backward(global_xx)

def right():
 global global_xx
 turtle.forward(global_xx)

def MySmile(A,global_xx,yy,wr):
 DrawCircle(A,global_xx+0*wr,yy-100*wr,150*wr,'green')
 DrawCircle(A,global_xx-40*wr,yy+60*wr,30*wr,'white')
 DrawCircle(A,global_xx-40*wr,yy+60*wr,10*wr,'black')
 DrawCircle(A,global_xx+50*wr,yy+60*wr,40*wr,'white')
 DrawCircle(A,global_xx+50*wr,yy+60*wr,10*wr,'black')
 DrawCircle(A,global_xx+0*wr,yy+20*wr,10*wr,'black')
 DrawCircle(A,global_xx+0*wr,yy-80*wr,40*wr,'brown')

MySmile(A,0,0,0.3)

screen.onkey(left, "Left") #this is keyboard code
screen.onkey(right, "Right")
screen.listen()

enter image description here

2 个答案:

答案 0 :(得分:0)

每次向左和向右移动时,调用渲染功能并清除屏幕。

,

答案 1 :(得分:0)

有两种方法可以解决此问题,但我认为最令人满意的方法是使用复合形状定义自定义乌龟光标。然后,我们将乌龟的形状更改为该自定义形状(倾斜)并将其像其他乌龟光标一样在屏幕上移动。

  

在trinket.io网站TypeError中不起作用:TypeError:   ()在第39行获得了意外的关键字参数“可见”   在main.py –박준영

这将永远不会 trinket.io 上运行,因为它缺少Shape类和创建自定义功能乌龟光标。您需要编辑问题以明确提及此约束。

让我们采用另一种方式,类似于@tomasantunes,但是我们将通过谨慎使用trinket.io支持的tracer()方法来使重绘瞬间完成:

from turtle import Screen, Turtle

global_xx = 0

def drawCircle(turtle, x, y, radius, color):
    turtle.goto(x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.circle(radius)
    turtle.end_fill()

def mySmile(turtle, x, y, wr):

    turtle.clear()

    drawCircle(turtle, x + 0 * wr, y - 100 * wr, 150 * wr, 'green')
    drawCircle(turtle, x - 40 * wr, y + 60 * wr, 30 * wr, 'white')
    drawCircle(turtle, x - 40 * wr, y + 60 * wr, 10 * wr, 'black')
    drawCircle(turtle, x + 50 * wr, y + 60 * wr, 40 * wr, 'white')
    drawCircle(turtle, x + 50 * wr, y + 60 * wr, 10 * wr, 'black')
    drawCircle(turtle, x + 0 * wr, y + 20 * wr, 10 * wr, 'black')
    drawCircle(turtle, x + 0 * wr, y - 80 * wr, 40 * wr, 'brown')

def left():
    global global_xx

    screen.onkey(None, 'Left')  # disable handler inside handler

    global_xx -= 10
    mySmile(turtle, global_xx, 0, 0.3)

    screen.update()
    screen.onkey(left, 'Left')

def right():
    global global_xx

    screen.onkey(None, 'Right')

    global_xx += 10
    mySmile(turtle, global_xx, 0, 0.3)

    screen.update()
    screen.onkey(right, 'Right')

screen = Screen()

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

mySmile(turtle, global_xx, 0, 0.3)

screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()

screen.tracer(0, 0)

screen.mainloop()