0

我有一个 tkinter gui,它有一个启动进程的按钮。在这个过程中有一个if语句,如果这个语句为真那么这个过程结束。当进程结束时,我希望 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()
4

2 回答 2

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()
于 2012-08-29T15:24:18.813 回答
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
于 2012-08-29T11:25:27.217 回答