Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我在将GUI导入python程序时遇到问题_Python_Sockets_User Interface_Tkinter - Fatal编程技术网

我在将GUI导入python程序时遇到问题

我在将GUI导入python程序时遇到问题,python,sockets,user-interface,tkinter,Python,Sockets,User Interface,Tkinter,我相信这是一个简单的修复,但我只是在这里间隔我的基本知识。我需要合并一个Gui,它可以简单地弹出并声明客户端和服务器之间已经建立了连接 我可以让GUI在我所有变量的代码顶部弹出,但它不会在我的代码下面运行,而我需要它显示的连接就是在代码下面定义的 # it will run but (address) is not defined yet import socket from tkinter import * root = Tk() theLabel = Label(root,text="Co

我相信这是一个简单的修复,但我只是在这里间隔我的基本知识。我需要合并一个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()
从socket导入AF\u INET、SOCK\u流、socket、gethostname
从tkinter进口*
从tkinter导入ttk
IP=gethostname()#或“127.0.0.1”
端口=1337
root=Tk()
根标题(“”)
mainframe=ttk.Frame(根,padding=“3 3 12”)
grid(列=0,行=0,粘性=(N,W,E,S))
root.columnconfigure(0,权重=1)
rowconfigure(0,权重=1)
对于大型机中的子级。winfo_children():
配置子网格(padx=5,pady=5)
root.bind(“”,connectionFunc)
def connectionFunc(*参数):
#这样你就不必关上插座了。
将套接字(AF_INET、SOCK_STREAM)作为s:
s、 听
s、 绑定((IP,端口))
conn,addr=s.accept()
康涅狄格州:
打印(f“连接自:{addr}”)
尽管如此:
数据=conn.recv(1024)
如果没有数据:
打破
conn.sendall(数据)
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()

root.mainloop()
在关闭窗口之前不会退出。您需要将其移动到程序的最后—您还需要将标签的创建移动到稍后的一点,以便您可以填写实际地址。GUI基本上完全在该调用中运行。您在GUI退出后运行的任何内容。您可能希望运行异步连接尝试,但我不确定如何将其与Tk的事件循环相匹配。可能有帮助(例如在之后使用
来安排投票)。虚拟事件可能是一种更干净的方式,但我不知道注入它们是否是线程安全的。