本文介紹了獲取調用事件的按鈕名稱的最佳方法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在以下代碼中(受 this 片段的啟發),我使用了一個事件處理程序 buttonClick
以更改窗口的標題.目前,我需要評估事件的 Id 是否對應于按鈕的 Id.如果我決定添加 50 個按鈕而不是 2 個,這種方法可能會變得很麻煩.有沒有更好的方法來做到這一點?
In the following code (inspired by this snippet), I use a single event handler buttonClick
to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method could become cumbersome. Is there a better way to do this?
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, 'wxBitmapButton',
pos=(300, 150), size=(300, 350))
self.panel1 = wx.Panel(self, -1)
self.button1 = wx.Button(self.panel1, id=-1,
pos=(10, 20), size = (20,20))
self.button1.Bind(wx.EVT_BUTTON, self.buttonClick)
self.button2 = wx.Button(self.panel1, id=-1,
pos=(40, 20), size = (20,20))
self.button2.Bind(wx.EVT_BUTTON, self.buttonClick)
self.Show(True)
def buttonClick(self,event):
if event.Id == self.button1.Id:
self.SetTitle("Button 1 clicked")
elif event.Id == self.button2.Id:
self.SetTitle("Button 2 clicked")
application = wx.PySimpleApp()
window = MyFrame()
application.MainLoop()
推薦答案
你可以給按鈕一個名字,然后在事件處理程序中查看這個名字.
You could give the button a name, and then look at the name in the event handler.
當你制作按鈕時
b = wx.Button(self, 10, "Default Button", (20, 20))
b.myname = "default button"
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
當按鈕被點擊時:
def OnClick(self, event):
name = event.GetEventObject().myname
這篇關于獲取調用事件的按鈕名稱的最佳方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!