我正在將舊的tkinter程序轉換爲wxPython。我使用tk的一件事是tk.IntVar()等。 wx中有沒有提供類似功能的東西?wxPython中是否有類似於tk.IntVar()的方法?
具體而言,我希望能夠定義模塊級別的變量,如myvar = tk.StringVar()
。然後,當這些變量被更新,都基於一個或多個用戶界面元素的更新上新的變量值,就像將與發生什麼:
self.score = tk.Entry(self, textvariable=myvar.get())
我正在將舊的tkinter程序轉換爲wxPython。我使用tk的一件事是tk.IntVar()等。 wx中有沒有提供類似功能的東西?wxPython中是否有類似於tk.IntVar()的方法?
具體而言,我希望能夠定義模塊級別的變量,如myvar = tk.StringVar()
。然後,當這些變量被更新,都基於一個或多個用戶界面元素的更新上新的變量值,就像將與發生什麼:
self.score = tk.Entry(self, textvariable=myvar.get())
這裏是你如何通常會安排您的應用程序....全局趨向是一個壞主意
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
謝謝,這似乎接近我想要的。然而,經過額外的研究後,我決定採用發佈者/訂閱者設計模式(特別是從PyPubSub http://pubsub.sourceforge.net/ - 他們有專門針對wx的示例,因此很容易)。 – dthor 2014-10-30 19:06:05
沒有theres沒有......但它沒有必要......只是像你的stringvar或任何'my_text.SetValue(「asdasdad」)'' – 2014-10-29 17:07:58
對待你的小工具好吧,但如果小部件深深的幀/面板層次結構,命名空間的東西會不會是一種痛苦?像'MainFrame.Panel1.Panel2.SubPanel.my_text.SetValue(「asasdasd」)'? – dthor 2014-10-29 17:16:18
雖然我想我可以設置'my_subpanel = MainFrame.Panel1.Panel2.SubPanel',然後執行'my_subpanel.my_text.SetValue(「asasdasd」)' – dthor 2014-10-29 17:18:08