[英]I am having trouble incorparating a GUI into my python program
我確定這是一個簡單的修復,但我只是在我的基礎上分開。 我需要合並一個簡單彈出的Gui,並聲明客戶端和服務器之間已建立連接。
我可以使用我的所有變量在我的代碼之上彈出GUI但它不會在我的代碼下面運行,這是我需要它顯示的連接的定義。
# it will run but (address) is not defined yet
import socket
from tkinter import *
root = Tk()
theLabel = Label(root,text="Connection from {address} has been established.")
theLabel.pack()
root.mainloop()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("HELL YEAH FAM!!! WE DID IT!!","utf-8"))
clientsocket.close()
它沒有錯誤消息,它只是不會運行GUI。
您必須配置所有內容,然后您可以為連接調用函數,然后在最后調用root.mainloop()。 以下是您需要完成的一些工作:
from socket import AF_INET, SOCK_STREAM, socket, gethostname
from tkinter import *
from tkinter import ttk
IP = gethostname() # or "127.0.0.1"
PORT = 1337
root = Tk()
root.title("")
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
root.bind('<Return>', connectionFunc)
def connectionFunc(*args):
# this way you dont have to close the socket.
with socket(AF_INET, SOCK_STREAM) as s:
s.listen()
s.bind((IP, PORT))
conn, addr = s.accept()
with conn:
print(f"connection from: {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
root.mainloop()
你應該使用線程來等待連接:
import socket
import threading
from tkinter import *
def wait_connection():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
msg.set(f"Connection from {address} has been established.")
clientsocket.send(bytes("HELL YEAH FAM!!! WE DID IT!!","utf-8"))
clientsocket.close()
root = Tk()
msg = StringVar(value='Waiting for connection ...')
theLabel = Label(root,textvariable=msg)
theLabel.pack()
# start a thread for waiting client connection
threading.Thread(target=wait_connection, daemon=True).start()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.