为什么socket.accept()没有显示Tkinter GUI?

时间:2019-06-02 17:47:40

标签: python python-3.x tkinter network-programming client-server

我正在尝试将客户端服务器软件包打包成一个应用程序。因此,当应用程序打开时,服务器会自动进入待机/监听模式。问题是运行服务器套接字时,它直到socket.accept()之后才显示gui。我希望gui和服务器套接字同时发生。

我已经注释掉了几行代码,直到conn,addr=s.accept()为止,它都能按预期工作

imports*

root= Tk()

#main config
#mouse drag
# ------------------ Server Socket ------------------
connectionStatus = Label(rootCanvasBG)
connectionStatus.grid(column=0, row=7)

s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host, port))
s.listen(10)
print(host)
print('waiting for connection')
connectionStatus.config(text='Waiting for any incoming connections')
conn, addr = s.accept()  # thread issue, not showing tkinter
connectionStatus.config(text=addr)
print(addr, 'connected')

#Layout

root.mainloop()

我已经阅读了有关解决该问题的线程的信息,但是我所见的示例都没有给出足够明确的答案。我对python和一般编程还是很陌生。谢谢

1 个答案:

答案 0 :(得分:0)

import threading   # <<< Import Threading

# ------------------ Server Socket ------------------

connectionStatus = Label(rootCanvasBG)
connectionStatus.grid(column=0, row=7)

s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host, port))
s.listen(10)
print(host)
print('waiting for connection')
connectionStatus.config(text='Waiting for any incoming connections')
def mainloop():   # <<< create a def
    while True:
        conn, addr = s.accept()  # thread issue, not showing tkinter
        connectionStatus.config(text=addr)
        print(addr, 'connected')
threading.Thread(target=mainloop).start() # <<< run loop on new thread

找到了解决方案,首先导入threadingdef mainloop()while loop创建一个conn, addr = s.accept() 使用threading.Thread()定位mainloop.start()来执行线程。