I am having trouble incorparating a GUI into my python program
You have to configure everything, then you can call a function for a connection and then at the end call root.mainloop(). Here are some of the work you need to make:
from socket import AF_INET, SOCK_STREAM, socket, gethostnamefrom tkinter import *from tkinter import ttkIP = gethostname() # or "127.0.0.1"PORT = 1337root = 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()
You should use thread for waiting connection:
import socketimport threadingfrom 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 connectionthreading.Thread(target=wait_connection, daemon=True).start()root.mainloop()