您可以從wx.Button
派生自己的類添加一個或多個屬性,使按鈕記住您想要的任何信息。
您可以在回調函數調用期間使用此存儲的信息。喜歡的東西:
import wx
L = [("1", "One"), ("2", "Two"), ("3", "Three")]
# =====================================================================
class MemoryButton(wx.Button):
def __init__(self, memory, *args, **kwargs):
wx.Button.__init__(self, *args, **kwargs)
self.memory = memory
# =====================================================================
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = wx.Panel(self)
self.buttons = []
for description in L:
button = MemoryButton(memory=description[1], parent=self.panel,
label=description[0])
button.Bind(wx.EVT_BUTTON, self.OnMemoryButton)
self.buttons.append(button)
self.sizer = wx.BoxSizer()
for button in self.buttons:
self.sizer.Add(button)
self.panel.SetSizerAndFit(self.sizer)
self.Show()
# -----------------------------------------------------------------
def OnMemoryButton(self, e):
print("Clicked '%s'" % e.GetEventObject().memory)
# =====================================================================
app = wx.App(False)
win = MainWindow(None)
app.MainLoop()
或者:
import wx
L = [("1", "One"), ("2", "Two"), ("3", "Three")]
# =====================================================================
class MemoryButton(wx.Button):
def __init__(self, memory, *args, **kwargs):
wx.Button.__init__(self, *args, **kwargs)
self.memory = memory
def OnButton(self, e):
print("Clicked '%s'" % self.memory)
# =====================================================================
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = wx.Panel(self)
self.buttons = []
for description in L:
button = MemoryButton(memory=description[1], parent=self.panel,
label=description[0])
button.Bind(wx.EVT_BUTTON, button.OnButton)
self.buttons.append(button)
self.sizer = wx.BoxSizer()
for button in self.buttons:
self.sizer.Add(button)
self.panel.SetSizerAndFit(self.sizer)
self.Show()
# =====================================================================
app = wx.App(False)
win = MainWindow(None)
app.MainLoop()
後續問題:我確定哪個按鈕被點擊後,我如何訪問相應的文本框讀取/寫入值?有沒有辦法將類似於我正在使用的文本框的指針列表存儲起來,然後遍歷該列表並比較每個文本框的名稱,直到找到合適的文本框? – anderspitman
I don不要以爲按鈕的支持客戶端數據,所以你最好創建一個字典,並使用按鈕的唯一名稱映射到文本控件,比如self.myDict = {「firstBtn」:firstTxt}。使用按鈕的名稱映射到文本控件。 –