如何用滑鼠移動 Tkinter 畫布?


Tkinter 畫布小部件是 Tkinter 庫中的一個功能多樣的小部件。它用於建立不同的圖形、影像和動畫物件。我們可以使用**move() **方法在畫布小部件上特定方向移動影像。

在 move(Image, x,y) 方法中定義影像和座標作為引數以在畫布中移動物件。我們全域性宣告影像以便移動或更改位置。

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

  • 首先,定義畫布小部件並向其新增影像。

  • 定義 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('logo.png'))
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)

# Define a function to allow the image to move within the canvas
def move(e):
   global image
   image = ImageTk.PhotoImage(Image.open('logo.png'))
   img = canvas.create_image(e.x, e.y, image=image)

# Bind the move function
canvas.bind("<B1-Motion>", move)

win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,其中包含一個可以使用滑鼠按鈕在視窗內進行移動的影像。

現在,單擊畫布並用滑鼠將物件拖動到周圍。

更新時間:2021 年 6 月 18 日

5000+ 瀏覽量

開啟你的 職業生涯

完成課程來獲得認證

開始吧
廣告
© . All rights reserved.