How to I disable the text ctrl when I select the c

2019-07-27 12:11发布

问题:

I want to achieve the effect that when I select the ComboBox to anonymous, the TextCtrl grays out. I want the TextCtrl object be local to the method set_name, I don't want tc be a member of the entire class. That is, how can I achieve this without change tc as self.tc? If it is possible, I also don't want to merge the two methods select_user_type and set_name as a single one.

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:

You have a couple options if you don't want to save the references directly on the class instance

1. save a reference outside of the instance ie

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. Alternatively you could save a reference to the textctrl directly on the combo box ie:

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