2014-07-25 109 views
2

我正在嘗試構建一個簡單的應用程序,該應用程序顯示基本的GUI並在後臺運行簡單的Web服務器。目前,我有這個代碼運行得很好:如何正確關閉使用線程的Tkinter應用程序

import Tkinter 
import SimpleHTTPServer 
import SocketServer 
import threading 
import time 
import webbrowser 
import json 

# Load configuration 
json_data=open('config.json') 
configuration = json.load(json_data) 
json_data.close() 


# ----------------------------------------- 
#   configuration 
# ----------------------------------------- 
host = configuration["host"] 
port = configuration["port"] 
folder = configuration["folder"] 
url = host + ":" + str(port) + "/" + folder 


# ----------------------------------------- 
#   Web Server 
# ----------------------------------------- 
class WebserverThread (threading.Thread): 
    def __init__(self, threadID, name): 
     threading.Thread.__init__(self) 
     self.threadID = threadID 
     self.name = name 

    def run(self): 
     self.PORT = port 
     self.Handler = SimpleHTTPServer.SimpleHTTPRequestHandler 
     self.httpd = SocketServer.TCPServer(("", self.PORT), self.Handler) 

     print "--- serving at port", self.PORT 
     self.httpd.serve_forever() 

    def close(self): 
     self.httpd.shutdown() 
     print "Exiting web server Thread" 

# create & start webserver thread, launch browser 
thread1 = WebserverThread(1, "Thread-1") 
thread1.start() 
webbrowser.open_new(url) 



# ----------------------------------------- 
#   Graphic User Interface 
# ----------------------------------------- 
# Create window 
top = Tkinter.Tk() 
top.geometry('200x200') 
top.resizable(width=0, height=0) 

# start GUI 
top.mainloop() 

# Handle exit 
print "Exiting Main Thread" 
thread1.close() 

如果我使用窗口關閉按鈕(在OSX紅圈),應用程序需要幾秒鐘,退出正確關閉GUI窗口。當我嘗試使用Cmd + Q關閉應用程序時,問題就出現了,在這種情況下,應用程序被凍結並且不會關閉(我需要強制關閉它,因爲它不會響應)。

我試着刪除Web服務器代碼(線程),問題不再發生,所以它看起來像東西一直在那裏運行,但我不知道如何處理它。

因此,本質上,當用戶嘗試通過Cmd + Q關閉應用程序時,如何處理並正確關閉應用程序?

非常感謝。

回答

0

我會Cmd的+ Q的事件和Tk一起的「綁定」命令

def callback(event): 
    print("Cmd-Q recieved, shutting down thread"); 
    thread1.close()  # stop the webServer thread 
    # call any additional exit handler you want 
    root.destroy()   # destroy root window, my syntax may be wrong here 

top.bind("<Cmd-Q>", callback) 

您可以決定如何將消息發送到您的webServerThread綁定。

相關問題