Tkinter Canvas 위젯은 Tkinter 라이브러리의 다양한 위젯 중 하나입니다. 다양한 모양, 이미지 및 애니메이션 개체를 만드는 데 사용됩니다. move() 를 사용하여 Canvas 위젯에 정의된 이미지에 동적 속성을 제공할 수 있습니다. 방법.
move(Image, x,y) 에서 이미지와 좌표를 매개변수로 정의 캔버스에서 이미지를 이동하는 방법입니다. 캔버스에서 이미지 위치를 추적하기 위해 이미지를 전역으로 선언합니다.
다음 단계에 따라 캔버스 내에서 이미지를 이동할 수 있습니다.
-
먼저 Canvas 위젯을 정의하고 여기에 이미지를 추가합니다.
-
move() 정의 이미지가 캔버스 내에서 동적으로 되도록 하는 기능입니다.
-
캔버스 내에서 이미지를 이동할 수 있는 기능으로 화살표 키를 묶습니다.
예시
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define a Canvas widget
canvas = Canvas(win, width=600, height=400, bg="white")
canvas.pack(pady=20)
# Add Images to Canvas widget
image = ImageTk.PhotoImage(Image.open('favicon.ico'))
img = canvas.create_image(250, 120, anchor=NW, image=image)
def left(e):
x = -20
y = 0
canvas.move(img, x, y)
def right(e):
x = 20
y = 0
canvas.move(img, x, y)
def up(e):
x = 0
y = -20
canvas.move(img, x, y)
def down(e):
x = 0
y = 20
canvas.move(img, x, y)
# Bind the move function
win.bind("<Left>", left)
win.bind("<Right>", right)
win.bind("<Up>", up)
win.bind("<Down>", down)
win.mainloop() 출력
위의 코드를 실행하면 화살표 키를 사용하여 창을 가로질러 이동할 수 있는 이미지가 포함된 창이 표시됩니다.

화살표 키로 캔버스의 개체를 이동할 수 있습니다.