Skip to main content
 首页 » 编程设计

python之Python 类的问题

2025年05月04日9think

好的,我真的是 python(和编程本身)的新手,很抱歉我的无知,但我真的需要问这个问题。 所以我在做一个 wxPython 项目,我在其中为笔记本添加了几个选项卡(笔记本的每个选项卡 = 一个类),并且有一个选项卡我在其中添加了一个复选框(在选项卡中,我们称之为 Tab1),以及我想要的是,当有人检查它时,存在于其他选项卡(例如 tab2 的类)中的按钮会隐藏在之前显示的位置。

好吧,我知道完成这个并不难,但我的问题是类(在本例中为 tab1 和 tab2)。我一直试图通过搜索来弄清楚,但我想我搜索得还不够努力,因为我就是做对了。如果他们在同一个类(class),我就不会有问题,但由于他们在不同的类(class),我对此感到非常挣扎。

希望有人能帮助我,再次为我的无知感到抱歉。

编辑:对不起,伙计们没有被显示/隐藏,而是被启用/禁用。

class Tab2(wx.Panel): 
    def __init__(self, parent): 
    ..... 
        self.jaddbutton = wx.Button(self,-1, label ="Button", size = (160,24)) 
        self.jaddbutton.Bind(wx.EVT_BUTTON, self.jaddbuttonclick, self.jaddbutton) 
    def jaddbuttonclick(self, event): 
        .... 
class Tab1(wx.Panel): 
    def __init__(self, parent): 
        self.jdcheck = wx.CheckBox(self, -1, 'Disable') 
        self.jdcheck.Bind(wx.EVT_CHECKBOX, self.checkoptions, self.jdcheck) 
    def checkoptions(self,event): 
        checkboxval = self.jdcheck.GetValue() 
        if checkboxval == False: 
            self.jaddbutton.Disable() # This is what I want to do but it is on the other class 
 
        else: 
            self.jaddbutton.Enable() # Same as above 
 
class TextFrame(wx.Frame): 
   def __init__(self): 
       p = wx.Panel(self) 
       self.nb = wx.Notebook(p, size = (750, 332)) 
       #Tabs 
       tab1 = Tab1(self.nb) 
       tab2 = Tab2(self.nb) 
       self.nb.AddPage(tab1, "ssomething") 
       self.nb.AddPage(tab2, "somethingr") 

请您参考如下方法:

这听起来更像是一个 wxpython 问题而不是类问题。通常,在 python 中,tab1 需要 tab2 的句柄才能隐藏 tab2 中的按钮。或者它需要一些共享资源的句柄,如父类或共享模型类,这将允许 tab1 影响 tab2 中的设置(如按钮的隐藏)。 PyQt 提供了一个事件系统来允许类之间的通信,这些类可能不一定包含彼此的句柄。在 wxpython 中常见的“公认”通信方式是什么?

这是共享父解决方案的一个相当抽象的示例。

class Parent(object): 
 
    def create_tabs(): 
        self.tab1 = Tab1(self) 
        self.tab2 = Tab2(self) 
 
    def hide_tab2_button(): 
        self.tab2.hide_button() 
 
 
class Tab1(object): 
    def __init__(self, parent): 
        self.parent = parent 
 
    def on_checkbox_checked(self): 
        self.parent.hide_tab2_button() 
 
 
class Tab2(object): 
    def __init__(self, parent): 
        self.parent = parent 
 
    def hide_button(self): 
       self.button.hide() # Or whatever the wxpython command is to hide a button.