移动已经绘制的图像python乌龟 [英] Move already drawn image python turtle
问题描述
是否可以在视觉上移动已经绘制的图像?每次移动时都不必重新绘制它?所以,让方块完好无损并朝某个方向移动.
Is it possible to visually move an already drawn image? Without having to redraw it each time it's moved? So, show the square intact and moving in some direction.
from turtle import *
def drawing():
forward(50)
left(90)
forward(50)
left(90)
forward(50)
left(90)
forward(50)
drawing()
done()
推荐答案
turtle
没有移动所有元素的特殊功能.
turtle
doesn't have special function to move all elements.
但是 turtle
使用 tkinter
,它使用 Canvas
对象来显示元素.Canvas
具有获取所有显示元素并移动它们的功能.
But turtle
uses tkinter
which uses Canvas
object to display elements.
Canvas
has function to get all displayed elements and move them.
turtle
可以访问画布(get_canvas()
),但稍后您必须了解 tkinter
才能对画布和元素执行某些操作.
turtle
gives access to canvas (get_canvas()
) but later you have to know tkinter
to do something with canvas and elements.
这个例子绘制元素然后它移动了(300, 50)
.
您也可以单击乌龟并拖动它来移动所有元素.
This example draw element and then it moves by (300, 50)
.
You can also click turtle and drag it to move all elements.
import turtle
t = turtle.Turtle()
# --- move all elements ---
def move(offset_x, offset_y):
canvas = turtle.getcanvas() # `turtle`, not `t`
for element_id in canvas.find_all():
canvas.move(element_id, offset_x, offset_y)
# --- move all on draging turtle ---
old_x = 0
old_y = 0
# get mouse current position
def on_click(x, y):
global old_x, old_y
old_x = x
old_y = y
# move elements
def on_drag(x, y):
global old_x, old_y
move(x-old_x, old_y-y)
old_x = x
old_y = y
t.onclick(on_click)
t.ondrag(on_drag)
# --- example ---
# draw something
for a in range(8):
for _ in range(8):
t.left(45)
t.fd(20)
t.right(45)
t.up()
t.fd(60)
t.down()
# move
move(300, 50)
# ---
turtle.done() # `turtle`, not `t`
这篇关于移动已经绘制的图像python乌龟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!