📜  Python Tkinter |使用 Canvas.move() 方法移动对象

📅  最后修改于: 2022-05-13 01:55:49.656000             🧑  作者: Mango

Python Tkinter |使用 Canvas.move() 方法移动对象

Tkinter 的Canvas 类支持用于在任何画布或 Tkinter 顶层中将对象从一个位置移动到另一个位置的函数。

我们将使用类来查看 move() 方法的工作原理。

类参数-

下面是Python的实现:

Python3
# imports every file form tkinter and tkinter.ttk
from tkinter import *
from tkinter.ttk import *
 
class GFG:
    def __init__(self, master = None):
        self.master = master
         
        # to take care movement in x direction
        self.x = 1
        # to take care movement in y direction
        self.y = 0
 
        # canvas object to create shape
        self.canvas = Canvas(master)
        # creating rectangle
        self.rectangle = self.canvas.create_rectangle(
                         5, 5, 25, 25, fill = "black")
        self.canvas.pack()
 
        # calling class's movement method to
        # move the rectangle
        self.movement()
     
    def movement(self):
 
        # This is where the move() method is called
        # This moves the rectangle to x, y coordinates
        self.canvas.move(self.rectangle, self.x, self.y)
 
        self.canvas.after(100, self.movement)
     
    # for motion in negative x direction
    def left(self, event):
        print(event.keysym)
        self.x = -5
        self.y = 0
     
    # for motion in positive x direction
    def right(self, event):
        print(event.keysym)
        self.x = 5
        self.y = 0
     
    # for motion in positive y direction
    def up(self, event):
        print(event.keysym)
        self.x = 0
        self.y = -5
     
    # for motion in negative y direction
    def down(self, event):
        print(event.keysym)
        self.x = 0
        self.y = 5
 
if __name__ == "__main__":
 
    # object of class Tk, responsible for creating
    # a tkinter toplevel window
    master = Tk()
    gfg = GFG(master)
 
    # This will bind arrow keys to the tkinter
    # toplevel which will navigate the image or drawing
    master.bind("", lambda e: gfg.left(e))
    master.bind("", lambda e: gfg.right(e))
    master.bind("", lambda e: gfg.up(e))
    master.bind("", lambda e: gfg.down(e))
     
    # Infinite loop breaks only by interrupt
    mainloop()


输出:

上面的代码中使用了额外的打印语句来显示move()方法的正确工作。 keysym关键字(Tkinter 保留)用于打印按下了哪个键盘键。