0

我正在将一个旧的 tkinter 程序转换为 wxPython。我大量使用的 tk 中的一件事是 tk.IntVar() 等。wx 中是否有提供类似功能的东西?

具体来说,我希望能够定义模块级变量,例如myvar = tk.StringVar(). 然后当这些变量更新时,根据新变量值更新一个或多个 UI 元素,就像会发生的情况一样:

self.score = tk.Entry(self, textvariable=myvar.get())
4

1 回答 1

2

这是您通常组织应用程序的方式....全局变量往往不是一个好主意

class MyNestedPanel(wx.Panel):
     def __init__(self,*a,**kw):
         ...
         self.user = wx.TextCtrl(self,-1)
      def SetUser(self,username):
         self.user.SetValue(username)

class MyMainPanel(wx.Panel):
      def __init__(self,*a,**kw):
          ...
          self.userpanel = MyNestedPanel(self,...)
      def SetUsername(self,username):
           self.userpanel.SetUser(username)

class MainFrame(wx.Frame):
      def __init__(self,*a,**kw):
           ...
           self.mainpanel = MyMainPanel(self,...)
      def SetUsername(self,username):
           self.mainpanel.SetUsername(username)

a = wx.App()
f = MainFrame(...)
f.Show()
a.MainLoop()

虽然你可以制作辅助功能

def set_widget_value(widget,value):
    if hasattr(widget,"SetWidgetValue"):
        return widget.SetWidgetValue(value) 
    if isinstance(widget,wx.Choice):
       return widget.SetStringSelection(value)
    if hasattr(widget,"SetValue"):
        return widget.SetValue(value)
    if hasattr(widget,"SetLabel"):
        return widget.SetLabel(value)
    else:
       raise Exception("Unknown Widget Type : %r"%widget)

def get_widget_value(widget):
     if hasattr(widget,"GetWidgetValue"):
        return widget.GetWidgetValue() 
     if isinstance(widget,wx.Choice):
        return widget.GetStringSelection()
     if hasattr(widget,"GetValue"):
        return widget.GetValue()
     if hasattr(widget,"GetLabel"):
        return  widget.GetLabel()
     else:
       raise Exception("Unknown Widget Type : %r"%widget)

class WidgetManager(wx.Panel):
      def __init__(self,parent):
         self._parent = parent
         wx.Panel.__init__(self,parent,-1)
         self.CreateWidgets()
      def CreateWidgets(self):
         #create all your widgets here
         self.widgets = {}
      def SetWidgetValue(self,value):
         if isinstance(value,dict):
            for k,v in value.items():
               set_widget_value(self.widgets.get(k),v)
         else:
            raise Exception("Expected a dictionary but got %r"%value)
      def GetWidgetValue(self):
          return dict([(k,get_widget_value(v))for k,v in self.widgets])

然后像这样使用它们https://gist.github.com/joranbeasley/37becd81ff2285fcc933

于 2014-10-29T17:49:15.920 回答