[英]tkinter move object on canvas
I'm new in python. 我是python的新手。 I'm trying to achieve a simple object movement on canvas. 我正在尝试在画布上实现简单的对象移动。
The idea is to simply update X, Y coordinates and redraw the oval. 想法是简单地更新X,Y坐标并重绘椭圆。
I've tried to use canvas.update()
every time I update coordinates but it doesn't work this way. 我尝试每次更新坐标时都使用canvas.update()
但是这种方式不起作用。
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()
Instead of character.x += 10
or character.y -= 10
, you need to use move
: 代替character.x += 10
或character.y -= 10
,您需要使用move
:
canvas.move(oval, 10, 0) # for x += 10
canvas.move(oval, 0, -10) # for y -= 10
The rest should follow. 其余应遵循。
Instead of a Character
class, you can just say oval = canvas.create_oval(x, y, x + 40, y + 40, fill=color)
. 您可以说oval = canvas.create_oval(x, y, x + 40, y + 40, fill=color)
代替Character
类。
**Please note: none of this code will work - it's just here to give you ideas about how to do stuff. **请注意:这些代码均无效-只是在这里为您提供有关操作方法的想法。 :) :)
I've had objects bound to the keyboard that move around the screen when buttons are pressed. 我有绑定到键盘的对象,这些对象在按下按钮时会在屏幕上移动。
instead of a loop, you can just change the x and y of an object with config and bind... when you press left on the keyboard the def will be run which moves the thing. 除了循环之外,您还可以使用config和bind更改对象的x和y ...当您在键盘上向左按时,将运行def来移动事物。 (or things) (或事物)
def move_object_left()...
object.config(move left...)
example of binding something: 绑定内容的示例:
entry.bind('<ButtonRelease-1>', lambda event: self.maximise_keyboard(event.widget))
x_var = 5 y_var = 9 x_var = 5 y_var = 9
**Bind an object to the keyboard here: **在此处将对象绑定到键盘:
*On_key_press('RIGHT'):
x_var = x_var + 5
object.config(x = x_var)
You can move a bunch of stuff at once if you want... (though you will have to do the code yourself lol) 如果需要,您可以一次移动一堆东西(尽管您必须自己编写代码,哈哈)
list_of_stuff = [tree, bush, snail] list_of_stuff = [树,灌木,蜗牛]
for entry in list_of_stuff:
...
**Get object X and Y of the object...
** add a number to this X and Y...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.