因此,我面臨并試圖解決的問題如下。我在這里使用這個人 (martineau) 的 tkinter 代碼的第二部分:使用滑鼠選擇影像區域并記錄選擇的尺寸
我已經獲取了代碼并將其設定為一個可呼叫的類,如下所示:
class select_area_class:
def __call__(self):
import tkinter as tk
from PIL import Image, ImageTk
WIDTH, HEIGHT = 900, 900
topx, topy, botx, boty = 0, 0, 0, 0
. . .
canvas.bind('<B1-Motion>', update_sel_rect)
window.mainloop()
問題是當這個函式被呼叫時:
def get_mouse_posn(event):
global topy, topx
topx, topy = event.x, event.y
. . .
(順便說一句,我已經洗掉了這個命令: global topy, topx因為它給我一個錯誤,所以,我把它變成了這樣:
def get_mouse_posn(event):
topx, topy = event.x, event.y
. . .
)
它不會更新主要值:topx, topy. 因此,無論我將滑鼠放在小部件內的任何位置,我都會得到 (0,0) 作為初始位置。我試圖回傳event.x, event.y,但我不知道如何從這個命令中讀取回傳值:
canvas.bind('<Button-1>', get_mouse_posn)
in order to update the main variables topx, topy and so to make the code work.... I have read both how canvas work (here: https://web.archive.org/web/20201108093851id_/http://effbot.org/tkinterbook/canvas.htm) and how bind works (here: https://web.archive.org/web/20201111211515id_/https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm ), but I cannot find a way to make it work. Any ideas?
uj5u.com熱心網友回復:
由于您使用了類,因此最好使用實體變數而不是全域變數。
還要更改get_mouse_posn()和update_sel_rect()類方法。
以下是基于您發布的代碼的簡單示例:
import tkinter as tk
from PIL import Image, ImageTk
class select_area_class:
def __call__(self):
window = tk.Tk()
WIDTH, HEIGHT = 900, 900
# use instance variables
self.topx, self.topy, self.botx, self.boty = 0, 0, 0, 0
self.canvas = tk.Canvas(window, width=WIDTH, height=HEIGHT)
self.canvas.pack()
self.canvas.bind('<Button-1>', self.get_mouse_posn)
self.canvas.bind('<B1-Motion>', self.update_sel_rect)
window.mainloop()
def get_mouse_posn(self, event):
self.topx, self.topy = self.botx, self.boty = event.x, event.y
self.rect_id = self.canvas.create_rectangle(self.topx, self.topy, self.botx, self.boty, outline='red')
def update_sel_rect(self, event):
self.botx, self.boty = event.x, event.y
self.canvas.coords(self.rect_id, self.topx, self.topy, self.botx, self.boty)
a = select_area_class()
a()
注意:是否有必要使類可呼叫?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425927.html
