运行以下代码时,该框快速出现并自动关闭。作业系统:Windows 10,Python3.6 有人可以帮我理解为什么会这样吗?
import sys, random, string, base64,time, calendar, io, threading, wx
try:
#Python 2.7
import thread
except ImportError:
#python 3.xx
import _thread as thread
class gameUI(wx.Frame):
def __init__(self):
self._rows = 0
self._columns = 0
self._user = None
app = wx.App()
wx.Frame.__init__(self, None, wx.ID_ANY, "Button Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
button = wx.Button(panel, id=wx.ID_ANY, label="Press Me")
button.Bind(wx.EVT_BUTTON, self.onButton)
def onButton(self, event):
"""
This method is fired when its corresponding button is pressed
"""
print ("Button pressed!")
def main():
# try:
# app = wx.App()
# frame = wx.Frame(None, title='Simple application')
# frame.Show()
# time.sleep(10)
# app.MainLoop()
try:
frame = gameUI()
frame.Show()
time.sleep(10)
app.MainLoop()
finally:
del app
if __name__ == '__main__':
main()
答案 0 :(得分:0)
在创建任何窗口之前,应先创建一个wx.App。
无需尝试使用finally删除应用程序,当所有窗口关闭时,垃圾收集器将删除该应用程序。
时间尚未导入,因此会出错,但您并不是真的要等待10秒才能使窗口响应,最好将其删除。
import wx
class gameUI(wx.Frame):
def __init__(self):
self._rows = 0
self._columns = 0
self._user = None
# app = wx.App() dont create app here
wx.Frame.__init__(self, None, wx.ID_ANY, "Button Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
button = wx.Button(panel, id=wx.ID_ANY, label="Press Me")
button.Bind(wx.EVT_BUTTON, self.onButton)
def onButton(self, event):
"""
This method is fired when its corresponding button is pressed
"""
print ("Button pressed!")
def main():
# try:
app = wx.App()
frame = gameUI()
frame.Show()
# time.sleep(10)
app.MainLoop()
# finally:
# del app not required
if __name__ == '__main__':
main()
答案 1 :(得分:0)
您仍然有问题。
MainLoop
开始之前,GUI不会显示,因此sleep
命令在错误的位置,如果将其放在MainLoop
之后,它将不会激活直到Gui关闭,即MainLoop
终止。 wx.App
的定义仍然不在通常的位置和位置
是,它仍然必须声明为self.app
,并且仍然必须称为frame.app
。 sizers
进行小部件定位,因此必须给每个小部件至少一个位置(如果没有大小的话)(它们会尝试自行调整大小)。尝试下面的代码,并注意区别。
import sys, random, string, base64,time, calendar, io, threading, wx
try:
#Python 2.7
import thread
except ImportError:
#python 3.xx
import _thread as thread
class gameUI(wx.Frame):
def __init__(self,parent,title):
self._rows = 0
self._columns = 0
self._user = None
wx.Frame.__init__(self, None, wx.ID_ANY, "Button Tutorial")
panel = wx.Panel(self, wx.ID_ANY)
button = wx.Button(panel, id=wx.ID_ANY, label="Press Me", pos=(20,20), size=(80,25))
quit = wx.Button(panel, id=wx.ID_ANY, label="Quit", pos=(20,50), size=(80,25))
button.Bind(wx.EVT_BUTTON, self.onButton)
quit.Bind(wx.EVT_BUTTON, self.onQuit)
def onButton(self, event):
"""
This method is fired when its corresponding button is pressed
"""
print ("Button pressed!")
def onQuit(self, event):
self.Destroy()
def main():
try:
app = wx.App()
frame = gameUI(None, title='Simple application')
frame.Show()
app.MainLoop()
finally:
del app
if __name__ == '__main__':
main()