wxPython中帧之间的全局变量

时间:2014-02-19 20:14:13

标签: python wxpython

我想使用子框架中定义的变量。我无法弄清楚如何在子帧中成功登录事件后将用户名拉回到主框架。我想更新静态标签以显示用户名。

import wx
import MySQLdb
import sys
username = ""

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title = 'Application Title',style = wx.SYSTEM_MENU)
        panel = wx.Panel(self)
        menubar = wx.MenuBar()
        panel.SetBackgroundColour((200,200,200))
        vbox = wx.BoxSizer(wx.HORIZONTAL)
        midPan = wx.Panel(panel)
        midPan.SetBackgroundColour((100,0,0))
        pan2 = wx.Panel(panel)
        pan2.SetBackgroundColour((0,100,0))
        vbox.Add(pan2, 1, wx.EXPAND | wx.ALL)
        vbox.Add(midPan, 5, wx.EXPAND | wx.ALL)
        hbox = wx.BoxSizer(wx.VERTICAL)
        hbox1=wx.BoxSizer(wx.VERTICAL)
        h1=wx.Panel(midPan)
        h1.SetBackgroundColour((200,0,100))
        h2=wx.Panel(midPan)
        h2.SetBackgroundColour((0,100,200))
#######################################################################
        text1 = wx.StaticText(h1, label="Welcome ") #insert the global variable in this label after the user has successfully logged in
        text2 = wx.StaticText(h1, label="Label2")
        hbox.Add(h1,3,wx.EXPAND|wx.ALL,20)
        hbox.Add(h2,1,wx.EXPAND|wx.ALL,20)
        hbox1.Add(text1,1,wx.ALIGN_LEFT)        
        hbox1.Add(text2,1,wx.ALIGN_RIGHT)  
        panel.SetSizer(vbox)
        midPan.SetSizer(hbox)
        h1.SetSizer(hbox1)
        self.statusbar = self.CreateStatusBar()
        self.SetMenuBar(menubar)
        self.Centre()
        self.Maximize()
        self.Show(True)
        frame = LoginFrame(self)
        frame.Show(True)
        frame.MakeModal(True)

    def OnExit(self, e):
        self.Close()

class LoginFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent,style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.MINIMIZE_BOX ), title = "System Login")
        self.panel = wx.Panel(self)     
        self.userlabel = wx.StaticText(self.panel, label="Username:")
        self.passlabel = wx.StaticText(self.panel, label="Password:")
        self.userbox = wx.TextCtrl(self.panel, size=(140, -1))
        self.passbox = wx.TextCtrl(self.panel, size=(140, -1), style=wx.TE_PASSWORD)
        self.login = wx.Button(self.panel, label="Login")
        self.exit = wx.Button(self.panel, label="Exit")
        self.Centre()
        self.windowSizer = wx.BoxSizer()
        self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)        
        self.sizer = wx.GridBagSizer(5, 5)
        self.sizer.Add(self.userlabel, (0, 0))
        self.sizer.Add(self.userbox, (0, 1))
        self.sizer.Add(self.passlabel, (1, 0))
        self.sizer.Add(self.passbox, (1, 1))
        self.sizer.Add(self.login, (2, 0))
        self.sizer.Add(self.exit, (2, 1))
        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.border)  
        self.SetSizerAndFit(self.windowSizer)  
        self.login.Bind(wx.EVT_BUTTON, self.OnLogin)
        self.exit.Bind(wx.EVT_BUTTON, self.OnExit)

    def OnLogin(self, e):
        db = MySQLdb.connect("localhost","root","","test" )
        cursor = db.cursor()
        username = self.userbox.GetValue()
        password = self.passbox.GetValue()
        try:
            cursor.execute("SELECT * FROM useraccounts WHERE username=%s" ,username)
            data = cursor.fetchall()
            for row in data:
                dbpass = row[2]
            if dbpass == password:
                self.MakeModal(False)
                e.Skip()
                self.Close()
                wx.MessageBox('You are now logged in', 'Info', wx.OK | wx.ICON_INFORMATION)
            else:
                wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)
        except:
            wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)

    def OnExit(self,e):
        self.MakeModal(False)
        e.Skip()
        self.Close()
        sys.exit(0)

if __name__ == '__main__':
    app = wx.App()
    MainFrame()
    app.MainLoop()

1 个答案:

答案 0 :(得分:1)

我认为最简单,最干净的方法是使用pubsub。 pubsub的API因您使用的wxPython版本而异。我已经为两者编写了教程。所以对于wxPython 2.8,你想看看这个:

对于wxPython 2.9+,你想看一下这个:

有一个技巧可以让wxPython 2.8以新的方式运行,我将在第二篇文章中解释。

无论如何,对于介绍来说,让我们在您的代码中尝试2.9方法:

import wx
import sys
username = ""
from wx.lib.pubsub import pub


class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title = 'Application Title',style = wx.SYSTEM_MENU)

        pub.subscribe(self.myListener, "update_frame")

        panel = wx.Panel(self)
        menubar = wx.MenuBar()
        panel.SetBackgroundColour((200,200,200))
        vbox = wx.BoxSizer(wx.HORIZONTAL)
        midPan = wx.Panel(panel)
        midPan.SetBackgroundColour((100,0,0))
        pan2 = wx.Panel(panel)
        pan2.SetBackgroundColour((0,100,0))
        vbox.Add(pan2, 1, wx.EXPAND | wx.ALL)
        vbox.Add(midPan, 5, wx.EXPAND | wx.ALL)
        hbox = wx.BoxSizer(wx.VERTICAL)
        hbox1=wx.BoxSizer(wx.VERTICAL)
        h1=wx.Panel(midPan)
        h1.SetBackgroundColour((200,0,100))
        h2=wx.Panel(midPan)
        h2.SetBackgroundColour((0,100,200))
#######################################################################
        self.text1 = wx.StaticText(h1, label="Welcome ") #insert the global variable in this label after the user has successfully logged in
        text2 = wx.StaticText(h1, label="Label2")
        hbox.Add(h1,3,wx.EXPAND|wx.ALL,20)
        hbox.Add(h2,1,wx.EXPAND|wx.ALL,20)
        hbox1.Add(self.text1,1,wx.ALIGN_LEFT)        
        hbox1.Add(text2,1,wx.ALIGN_RIGHT)  
        panel.SetSizer(vbox)
        midPan.SetSizer(hbox)
        h1.SetSizer(hbox1)
        self.statusbar = self.CreateStatusBar()
        self.SetMenuBar(menubar)
        self.Centre()
        self.Maximize()
        self.Show(True)
        frame = LoginFrame(self)
        frame.Show(True)
        frame.MakeModal(True)

    #----------------------------------------------------------------------
    def myListener(self, msg):
        """"""
        self.text1.SetLabel("Welcome %s" % msg)

    def OnExit(self, e):
        self.Close()

class LoginFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent,style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.MINIMIZE_BOX ), title = "System Login")
        self.panel = wx.Panel(self)     
        self.userlabel = wx.StaticText(self.panel, label="Username:")
        self.passlabel = wx.StaticText(self.panel, label="Password:")
        self.userbox = wx.TextCtrl(self.panel, size=(140, -1))
        self.passbox = wx.TextCtrl(self.panel, size=(140, -1), style=wx.TE_PASSWORD)
        self.login = wx.Button(self.panel, label="Login")
        self.exit = wx.Button(self.panel, label="Exit")
        self.Centre()
        self.windowSizer = wx.BoxSizer()
        self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)        
        self.sizer = wx.GridBagSizer(5, 5)
        self.sizer.Add(self.userlabel, (0, 0))
        self.sizer.Add(self.userbox, (0, 1))
        self.sizer.Add(self.passlabel, (1, 0))
        self.sizer.Add(self.passbox, (1, 1))
        self.sizer.Add(self.login, (2, 0))
        self.sizer.Add(self.exit, (2, 1))
        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.border)  
        self.SetSizerAndFit(self.windowSizer)  
        self.login.Bind(wx.EVT_BUTTON, self.OnLogin)
        self.exit.Bind(wx.EVT_BUTTON, self.onClose)
        self.Bind(wx.EVT_CLOSE, self.onClose)

    def OnLogin(self, e):
        #db = MySQLdb.connect("localhost","root","","test" )
        #cursor = db.cursor()
        username = self.userbox.GetValue()
        password = self.passbox.GetValue()
        #self.MakeModal(False)

        self.Close()
        #try:
            #cursor.execute("SELECT * FROM useraccounts WHERE username=%s" ,username)
            #data = cursor.fetchall()
            #for row in data:
                #dbpass = row[2]
            #if dbpass == password:
                #
                #e.Skip()
                #self.Close()
                #wx.MessageBox('You are now logged in', 'Info', wx.OK | wx.ICON_INFORMATION)
            #else:
                #wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)
        #except:
            #wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)

    def onClose(self,e):
        username = self.userbox.GetValue()
        pub.sendMessage("update_frame", msg=username)
        self.Destroy()


if __name__ == '__main__':
    app = wx.App()
    MainFrame()
    app.MainLoop()

此代码在Windows 7上使用wxPython 2.9和Python 2.7。请注意,我注释掉了SQL的内容,使其运行起来更简单一些。我也稍微改变了事件绑定,因为OnExit并没有为我开火。