gpt4 book ai didi

python - 我无法将 GUI 合并到我的 python 程序中

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:13 26 4
gpt4 key购买 nike

我确信这是一个简单的修复,但我只是在我的基础知识上停顿了一下。我需要合并一个 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()

关于python - 我无法将 GUI 合并到我的 python 程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57171319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com