Domanda

Sto avendo un po 'di problemi con un pannello che contiene due wxPython TextCtrls. Voglio un gestore EVT_CHAR o EVT_KEY_UP associato a entrambi i controlli e voglio essere in grado di dire quale TextCtrl ha generato l'evento. Penserei a quell'evento. Lo direi, ma nel seguente codice di esempio è sempre 0. Qualche idea? L'ho provato solo su OS X.

Questo codice verifica semplicemente che entrambi TextCtrls contengano del testo prima di abilitare il pulsante Fine

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title,
                         wx.DefaultPosition, wx.Size(200, 150))
        self.panel = BaseNameEntryPanel(self)

class BaseNameEntryPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        self.entry = wx.TextCtrl(self, wx.NewId())
        self.entry2 = wx.TextCtrl(self, wx.NewId())

        self.donebtn = wx.Button(self, wx.NewId(), "Done")
        self.donebtn.Disable()

        vsizer = wx.BoxSizer(wx.VERTICAL)

        vsizer.Add(self.entry, 1, wx.EXPAND|wx.GROW)
        vsizer.Add(self.entry2, 1, wx.EXPAND|wx.GROW)
        vsizer.Add(self.donebtn, 1, wx.EXPAND|wx.GROW)
        self.SetSizer(vsizer)
        self.Fit()
        self.entry.Bind(wx.EVT_KEY_UP, self.Handle)
        self.entry2.Bind(wx.EVT_KEY_UP, self.Handle)


    def Handle(self, event):
        keycode = event.GetKeyCode()
        print keycode, event.Id # <- event.Id is always 0!

        def checker(entry):
            return bool(entry.GetValue().strip())

        self.donebtn.Enable(checker(self.entry) and checker(self.entry2))



class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Hello from wxPython")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()
È stato utile?

Soluzione

Puoi provare event.GetId () o event.GetEventObject () e vedere se una di queste funzioni.

Un altro approccio a questo è usare lambda o functools.partial per passare efficacemente un parametro al gestore. Quindi, ad esempio, inserisci le righe sottostanti nel tuo programma:

        self.entry.Bind(wx.EVT_KEY_UP, functools.partial(self.Handle, ob=self.entry))
        self.entry2.Bind(wx.EVT_KEY_UP, functools.partial(self.Handle, ob=self.entry2))

    def Handle(self, event, ob=None):
            print ob

E poi ob sarà entry o entry2 a seconda del pannello su cui si fa clic. Ma, naturalmente, questo non dovrebbe essere necessario e GetId e GetEventObject () dovrebbero funzionare entrambi, anche se non ho (ancora) un Mac per provarli.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top