wxPython 專案中,MyButton 需調用 TextBox 的 Clear() 方法,但兩者為獨立類,尚未建立實例關係。
在包含兩者的容器類(如主視窗)中建立實例並互相引用:
class MainFrame(wx.Frame):
def __init__(self):
self.text_box = TextBox(self)
self.my_button = MyButton(self)
# 將 text_box 引用傳給 button
self.my_button.set_text_box(self.text_box)
class MyButton(wx.Button):
def __init__(self, parent):
super().__init__(parent, label='清空')
self.text_box = None
self.Bind(wx.EVT_BUTTON, self.on_click)
def set_text_box(self, text_box):
self.text_box = text_box
def on_click(self, event):
if self.text_box:
self.text_box.Clear()
若組件眾多,可引入 pubsub 或自訂事件總線:
from pubsub import pub
# Button 發布事件
pub.sendMessage('clear_text')
# TextBox 訂閱
pub.subscribe(self.Clear, 'clear_text')
實現完全解耦,適合大型 GUI 架構。