Wxpython - bind events in external files

I am trying to bind events from a GUI file to use code from another file (actually "front end" and "end"). I can get the back and front ends working in the same file, but when I try to move them to separate files, I have problems with the back end to see the parts (labels, buttons, etc.) of the Front end.

I am. E. I need the end-of-code code for changing labels and doing math, etc., And that should affect the graphical interface.

I have provided a simple version of my program. Everything works, except for the error I get when I try to make the back end part of the parts of the GUI.

mainfile.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx

import label_changer

class foopanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY)

        box = wx.BoxSizer()
        btn = wx.Button(self,1,"Press")
        btn.Bind(wx.EVT_BUTTON,label_changer.change_label(self))
        box.Add(btn)

        self.lbl = wx.StaticText(self,1,"Foobar")
        box.Add(self.lbl)

        self.SetSizerAndFit(box)

class main_frame(wx.Frame):
    """Main Frame holding the main panel."""
    def __init__(self,*args,**kwargs):
        wx.Frame.__init__(self,*args,**kwargs)

        sizer = wx.BoxSizer()

        self.p = foopanel(self)

        sizer.Add(self.p,1)

        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    frame = main_frame(None,-1,)
    app.MainLoop()

label_changer.py

def change_label(self):
    self.p.lbl.SetLabel("barfoo")

, , GUI, .

, .

!

+3
3

MVC Pattern pubsub. . .

+1

change_label, , . :

def change_label(event, label):
    label.SetLabel("barfoo")

lambda , :

btn.Bind(wx.EVT_BUTTON, label_changer, 
    lambda event, label=self.p.lbl: label_changer.change_label(event, label))

, self.lbl, .

. WxPyWiki

+2

btn.Bind(wx.EVT_BUTTON,label_changer.change_label(self))

btn.Bind(wx.EVT_BUTTON,label_changer.change_label)

def change_label(self):
    self.p.lbl.SetLabel("barfoo")

def change_label(event):
    panel = event.GetEventObject().GetParent()
    panel.lbl.SetLabel("barfoo")

, Bind, . wx - . self, , . ( , , ) , . , "" , .

One more thing, you do not really separate gui from logic this way. This is because the logic (label_changer in this case) needs to know about gui and manipulate it directly. There are ways to achieve a much stronger separation (st2053 hinted at one of them), but for a relatively small program you do not need to worry if you do not want it now, just by breaking the code into several files and focusing on getting things done right. You may worry about architecture later.

0
source

All Articles