获取调用事件的按钮名称的最佳方法?

2024-06-16 13:57:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中(受this代码片段的启发),我使用单个事件处理程序buttonClick来更改窗口的标题。目前,我需要评估事件的Id是否与按钮的Id对应。如果我决定添加50个按钮而不是2个,这个方法可能会变得很麻烦。有更好的办法吗?

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

Tags: 代码posselfeventidsize事件button
3条回答

您可以给按钮命名,然后查看事件处理程序中的名称。

当你按下按钮时

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

利用像Python这样的语言所能做的事情。您可以像这样向事件回调函数传递额外的参数。

import functools

def __init__(self):
    # ...
    for i in range(10):
        name = 'Button %d' % i
        button = wx.Button(parent, -1, name)
        func = functools.partial(self.on_button, name=name)
        button.Bind(wx.EVT_BUTTON, func)
    # ...

def on_button(self, event, name):
    print '%s clicked' % name

当然,争论可以是任何你想要的。

我建议您使用不同的事件处理程序来处理每个按钮中的事件。如果有很多共同点,可以将其组合成一个函数,该函数返回具有所需特定行为的函数,例如:

def goingTo(self, where):
    def goingToHandler(event):
        self.SetTitle("I'm going to " + where)
    return goingToHandler

def __init__(self):
    buttonA.Bind(wx.EVT_BUTTON, self.goingTo("work"))
    # clicking will say "I'm going to work"
    buttonB.Bind(wx.EVT_BUTTON, self.goingTo("home"))
    # clicking will say "I'm going to home"

相关问题 更多 >