wxPython app: No error but still freezes

2019-08-19 06:41发布

问题:

I don't get any errors with my code, but after I hit the spam button it freezes and nothing happens. Does anyone see anything wrong with the code?

    import Skype4Py, wx, time as t


    skype = Skype4Py.Skype()
    skype.Attach()
    name = ""
    chat = ""
    message = ""


    class skyped(wx.Frame):

        def __init__(self,parent,id):
            wx.Frame.__init__(self,parent,id,"Skype Chat Spammer",size=(300,200))
            panel=wx.Panel(self)
            start=wx.Button(panel,label="Spam!",pos=(140,100),size=(50,20))
            stop=wx.Button(panel,label="Stop!", pos=(200,100),size=(50,20))
            self.Bind(wx.EVT_BUTTON, self.spam, start)
            self.Bind(wx.EVT_CLOSE, self.closewindow)
            entered=wx.TextEntryDialog(None, "User to spam?", "User", "Username Here")
            if entered.ShowModal()==wx.ID_OK:
                name=entered.GetValue()
            entered1=wx.TextEntryDialog(None, "Message?", "Message", "Message Here")
            if entered1.ShowModal()==wx.ID_OK:
                message=entered1.GetValue()

        def spam(self,event):
            global chat
            global name
            global message
            chat = skype.CreateChatWith(name)
            while 1:
                chat.SendMessage(message)

        def closewindow(self,event):
            self.Destroy()

    if __name__=="__main__":
        app=wx.PySimpleApp()
        frame=skyped(parent=None,id=-1)
        frame.Show()
        app.MainLoop()

回答1:

Building off of kotlinski's answer, yes its freezing because you are doing an endless loop in the main thread of your application. The app can no longer process any gui-related interaction or events.

While I don't know much wx, the theory is the same as PyQt. You should never block the main thread of your app with any long running or heavy lifting operations. Those should be run in separate threads and communicating back with signals:

http://wiki.wxpython.org/LongRunningTasks

Your main thread should always be clear to handle user interaction with the widgets.



回答2:

It probably freezes because your application goes into an endless loop here:

    while 1:
        chat.SendMessage(message)