本文介绍了tkinter 在画布上移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Python 新手.我正在尝试在画布上实现简单的对象移动.
I'm new in python. I'm trying to achieve a simple object movement on canvas.
这个想法是简单地更新 X、Y 坐标并重新绘制椭圆.
The idea is to simply update X, Y coordinates and redraw the oval.
每次更新坐标时我都尝试使用 canvas.update()
但它不能这样工作.
I've tried to use canvas.update()
every time I update coordinates but it doesn't work this way.
class character():
x = 10
y = 10
color = "red"
canvas.create_oval(x, y, x + 40, y + 40, fill=color)
def moveup():
character.y -= 10
def moveright():
character.x += 10
def movedown():
character.y += 10
def moveleft():
character.x -= 10
def choose():
choosen_move = randint(0, 4)
if choosen_move == 0:
moveup()
elif choosen_move == 1:
moveright()
elif choosen_move == 2:
movedown()
elif choosen_move == 3:
moveleft()
print "%s | %s" % (character.x, character.y)
canvas.update()
sleep(1)
while True:
choose()
root.mainloop()
推荐答案
代替 character.x += 10
或 character.y -= 10
,你需要使用 move
:
Instead of character.x += 10
or character.y -= 10
, you need to use move
:
canvas.move(oval, 10, 0) # for x += 10
canvas.move(oval, 0, -10) # for y -= 10
剩下的应该跟上.
代替 Character
类,您可以只说 oval = canvas.create_oval(x, y, x + 40, y + 40, fill=color)
.
Instead of a Character
class, you can just say oval = canvas.create_oval(x, y, x + 40, y + 40, fill=color)
.
这篇关于tkinter 在画布上移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!