将组合框选择为特定值时,如何禁用文本ctrl?

时间:2018-12-17 14:45:45

标签: python user-interface wxpython wxpython-phoenix

我想实现以下效果:当我选择ComboBoxanonymous时,TextCtrl变灰。我希望TextCtrl对象位于方法set_name的本地,我不希望tc成为整个类的成员。也就是说,如何在没有方法的情况下实现此目标将tc更改为self.tc?如果可能的话,我也不想将两个方法select_user_typeset_name合并为一个。

import wx


class Example(wx.Frame):

    def __init__(self, title):
        super().__init__(None, title=title)
        self.panel = wx.Panel(self)
        self.initUI()

    def initUI(self):
        sizer = wx.GridBagSizer(2, 2)
        self.select_user_type(sizer)
        self.set_name(sizer)
        self.panel.SetSizer(sizer)
        sizer.Fit(self)

    def select_user_type(self, sizer):
        user_type = ['normal', 'anonymous']
        combo = wx.ComboBox(self.panel, choices=user_type)
        sizer.Add(combo, pos=(0, 1), span=(1, 2), flag=wx.TOP|wx.EXPAND, border=5)
        combo.Bind(wx.EVT_COMBOBOX, self.on_user_type)

    def set_name(self, sizer):
        text1 = wx.StaticText(self.panel, label="Enter your name:")
        sizer.Add(text1, pos=(1, 0), flag=wx.LEFT | wx.TOP | wx.BOTTOM, border=10)
        tc1 = wx.TextCtrl(self.panel, style=wx.TE_CENTER, value="enter_name_here")
        tc1.Bind(wx.EVT_TEXT, self.on_get_text)
        sizer.Add(tc1, pos=(1, 1), flag=wx.TOP|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=5)

    def on_get_text(self, e):
        tc = e.GetEventObject()
        print(tc.GetValue())

    def on_user_type(self, e):
        print("how to disable text ctrl when I select anonymous")


if __name__ == '__main__':
    app = wx.App()
    Example("Example").Show()
    app.MainLoop()

1 个答案:

答案 0 :(得分:1)

如果不想直接将引用保存在类实例上,则有两种选择

1。 将引用保存在实例外部,即

import wx

combo_tc_map = {}

class Example(wx.Frame):
    self.panel = wx.Panel(self)
    combobox = wx.ComboBox(self.panel)
    textctrl = wx.TextCtrl(self.panel)
    # references are saved in a module level dict
    combo_tc_map[combobox] = textctrl
    combobox.Bind(wx.EVT_COMBOBOX, self.on_user_type)


    def on_user_type(self, e):
        combo = e.GetEventObject()
        tc = combo_tc_map[combo]
        tc.Disable()

2。 或者,您可以直接在组合框上保存对textctrl的引用,即:

import wx


class Example(wx.Frame):
    self.panel = wx.Panel(self)
    combobox = wx.ComboBox(self.panel)
    textctrl = wx.TextCtrl(self.panel)
    # reference is saved directly to the ComboBox
    combobox._linked_textctrl = textctrl
    combobox.Bind(wx.EVT_COMBOBOX, self.on_user_type)

    def on_user_type(self, e):
        combo = e.GetEventObject()
        tc = combo._linked_textctrl
        tc.Disable()