You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter:父类方法执行后如何回调子类方法?

实现Popup的right_click后调用子类main的click方法

这里提供两种可行的实现方案,按需选择即可:

方案一:给Popup类添加回调参数

通过在Popup的初始化方法中传入回调函数,让right_click执行时触发子类的逻辑,这种方式耦合度更低,Popup类的复用性更强:

import tkinter
from tkinter import Menu

class Popup(Menu):
    # 新增callback参数,默认值为None
    def __init__(self, parent, callback=None):
        Menu.__init__(self, parent, tearoff=0)
        self.callback = callback
        self.add_command(label='click', command=self.right_click)

    def popup(self, x, y):
        try:
            self.tk_popup(x, y)
        finally:
            self.grab_release()
    
    def right_click(self):
        print('Click!')
        # 如果传入了回调函数则执行
        if self.callback:
            self.callback()


class main(Popup):
    def __init__(self) -> None:
        main_window = tkinter.Tk()
        self.label = tkinter.Label(main_window, text='test')
        self.label.pack()
        # 将子类的click方法作为回调传入Popup
        Popup.__init__(self, main_window, callback=self.click)
        self.label.bind('<ButtonRelease-3>', lambda event: self.popup(event.x_root, event.y_root))
        main_window.mainloop()
    
    def click(self):
        self.label.config(text='click')


main()

方案二:在子类main中重写right_click方法

利用面向对象的继承特性,子类直接覆盖父类的right_click方法,先执行父类原有逻辑,再调用自身的click方法:

import tkinter
from tkinter import Menu

class Popup(Menu):
    def __init__(self, parent):
        Menu.__init__(self, parent, tearoff=0)
        self.add_command(label='click', command=self.right_click)

    def popup(self, x, y):
        try:
            self.tk_popup(x, y)
        finally:
            self.grab_release()
    
    def right_click(self):
        print('Click!')


class main(Popup):
    def __init__(self) -> None:
        main_window = tkinter.Tk()
        self.label = tkinter.Label(main_window, text='test')
        self.label.pack()
        Popup.__init__(self, main_window)
        self.label.bind('<ButtonRelease-3>', lambda event: self.popup(event.x_root, event.y_root))
        main_window.mainloop()
    
    def click(self):
        self.label.config(text='click')
    
    # 重写父类的right_click方法
    def right_click(self):
        # 先执行父类的原有逻辑
        super().right_click()
        # 再调用子类的click方法
        self.click()


main()

内容的提问来源于stack exchange,提问作者cloud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:43:25