在python画布中移动定义的对象

2024-09-27 04:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我不想移动画布上定义的对象。我知道有一个命令可以移动一个对象(.move)或者它只对单个项目有效。那么我怎样才能移动一个由矩形组成的完整的物体呢? 就像例子中的那个?因为我需要移动成百上千个小物体。在

x=400
y=400



def player(x,y):
    canvas.create_rectangle(x,y,x+50,y+50,fill='black')
    canvas.create_rectangle(x,y+50,x+150,y+150,fill='red')


def moveright(coordinates2):
    global x
    global y
    x=x+200
    y=y+0
    player(x,y)

def moveleft(coordinates3):
    global x
    global y
    x=x-200
    y=y+0
    player(x,y)

def moveup(coordinates4):
    global x
    global y
    x=x+0
    y=y-150
    player(x,y)

def moveright(coordinates5):
    global x
    global y
    x=x+0
    y=y+150
    player(x,y)



canvas.bind_all('<Right>',moveright)
canvas.bind_all('<Left>',moveleft)
canvas.bind_all('<Up>',moveup)
canvas.bind_all('<Down>',movedown)

Tags: 对象binddef画布createallfillglobal
1条回答
网友
1楼 · 发布于 2024-09-27 04:20:39

与您在问题中所说的不同,move如果您使用标记:canvas.move(<tag or id>, x, y),则对一组项目有效。在

下面是一个例子:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()


def move():
    # move all items with the 'group' tag
    canvas.move('group', 10, 10)


canvas.create_rectangle(10, 10, 30, 30, tags=['group'])
canvas.create_rectangle(20, 40, 50, 70, tags=['group'])
canvas.create_rectangle(60, 50, 80, 60, tags=['group'])

tk.Button(root, text='Move', command=move).pack()
root.mainloop()

相关问题 更多 >

    热门问题