Return 来自嵌套函数的值并更新可调用 class 中的主要值

Return values from a nested function and update the main values inside a callable class

所以,我面临的问题和我正在尝试解决的问题如下。我在这里使用这个人(martineau)的 tkinter 代码的第二部分:

我已获取代码并使其成为可调用的 class,如下所示:

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) 作为初始位置。我试过 return event.x, event.y 但我不知道如何从这个命令中读取 return 值:

canvas.bind('<Button-1>', get_mouse_posn)

为了更新主要变量 topx, topy 并使代码正常工作....我已经阅读了 canvas 的工作原理(此处: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),但是我找不到让它工作的方法。有什么想法吗?

既然用了class,不如用实例变量代替全局变量.

同时将 get_mouse_posn()update_sel_rect() 更改为 class 方法。

下面是一个基于您发布的代码的简单示例:

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

注意:是否有必要使 class 可调用?