结束python代码没有错误让Gui打开

时间:2012-08-29 10:50:00

标签: python user-interface tkinter

我有一个tkinter gui,它有一个启动进程的按钮。在此过程中有一个if语句,如果此语句为true,则该过程结束。当进程结束时,我希望GUI保持打开状态并且不显示错误。我已经尝试了os._exit()但它也关闭了gui。

from Tkinter import *
import tkMessageBox
def Program():
#Process
#Process
    if #something happens#:
       #Stop process but keep gui open and dont show errors
root = Tk()
root.title("GUI")
root.geometry('450x300+200+200')
labelText=StringVar()
labelText.set("Program")
label1=Label(root,textvariable=labelText,height=4)
label1.pack()
mbutton=Button(text='Start Program',command=Model).pack()
root.mainloop()

2 个答案:

答案 0 :(得分:0)

您可以在主线程中运行GUI,并将应该独立终止的部分放在后台线程中。在线程中添加try / except以抑制回溯,例如:

import threading

def bgthread(gui_ready, result_queue):
    gui_ready.wait()
    while True:
       try:
           # do some work ...
           result_queue.put(result) # GUI gets results e.g., 
                                    # via q.get_nowait() in a
                                    # widget.after() callback 
           if something_happened():
              break # exit
       except: #NOTE: don't use bare except unless it is absolutely necessary
           logger.error() # log to file
           break # exit

# setup logging          
# ...
ready = threading.Event()
q = Queue.Queue()
threading.Thread(target=bgthread, args=(ready,q)).start()

# setup gui here
...
root.mainloop() # call ready.set() in some GUI code then it is ready

答案 1 :(得分:0)

Python代码使用geo_pythoncl建议使用return。

from Tkinter import * 
import tkMessageBox 
def Program(): 
#Process 
#Process     
 if #something happens#:        
 #Stop process but keep gui open and dont show errors 
 return
root = Tk() 
root.title("GUI") 
root.geometry('450x300+200+200') 
labelText=StringVar() 
labelText.set("Program") 
label1=Label(root,textvariable=labelText,height=4) 
label1.pack() 
mbutton=Button(text='Start Program',command=Model).pack() 
root.mainloop()