如何在 Tkinter 畫布中使用方向鍵移動影像?


Tkinter Canvas 小部件是 Tkinter 庫中用途廣泛的小部件之一。它用於建立不同的形狀、影像和動畫物件。我們可以使用 **move()** 方法為在 Canvas 小部件中定義的影像提供動態屬性。

在 **move(Image, x,y)** 方法中將影像和座標定義為引數,以在 Canvas 中移動影像。我們全域性宣告影像以便跟蹤 Canvas 中的影像位置。

我們可以按照以下步驟使影像在畫布內可移動,

  • 首先,定義 Canvas 小部件並在其中新增影像。

  • 定義 **move()** 函式以允許影像在 Canvas 內動態變化。

  • 將方向鍵繫結到允許影像在 Canvas 內移動的函式。

示例

# 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()

輸出

執行以上程式碼將顯示一個視窗,其中包含一個可以使用方向鍵在視窗中移動的影像。

您可以使用方向鍵在畫布上移動物件。

更新於:2021年6月18日

4K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告