Python 3 global Function from within inside a threaded function

Hello all,

In my spare time I am coding a socket messenger using the Tkinter Python module for its GUI.
It was mostly created just message my friends at school, however I ran into a problem

As the Tkinter module requires the mainloop() function in order to display the GUI, the "while True:" statement / loop is needed to run alongside this function in order to supply the GUI with information to display messages and so forth.

After some googling, I found "threading". I am not too sure on how this works, but it seems I have managed to muddle up how to declare a global function (needed as a callback for the "Send" button).

Here is my program:

import section

from tkinter import*
import socket, random, base64, os, threading, time

def connection_loop():
global Send
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 1144
s.bind((host,port))
s.listen(1)

while True:
    def Send(Var):
        Var = Send_Var
        c.send(Var.encode("utf-8"))

    c, laddr = s.accept()
    swprint("Got Connection from" + str(laddr))
    Client_Message = c.recv(1024)
    Client_Message = Client_Message.decode("utf-8")
    swprint("Client: " + Client_Message)

graphics management

root = Tk()
root.resizable(height = False, width = False)
root.wm_title("Spider Host")
f = Frame(root, height = 300, width = 400)
w = Text(root, bd = 2, font = ("Comic Sans",10," bold"), fg = "blue")
e = Entry(root, bg = "white", fg = "blue", bd = 2, font = ("Comic Sans",10," bold"))
b = Button(root, bg = "dark blue", fg = "white", bd = 2, text = "Send", command = Send(e.get()))
sc = Scrollbar(root, bd = 2)

f.pack()
f.configure(bg = "white")
sc.config(command = w.yview)
w.place(relx = 0, rely = 0, relheight = 0.9, relwidth = 1)
e.place(relx = 0, rely = 0.9, relheight = 0.1, relwidth = 0.85)
b.place(relx = 0.85, rely = 0.9, relheight = 0.1, relwidth = 0.15)
sc.place(relx = 0.98, rely = 0, relheight = 0.9, relwidth = 0.02)

thread = threading.Thread(target = connection_loop)
thread.daemon = True
thread.start()
mainloop()

(and just to clarify yes I have created a client capable of connecting to the host)

ahh yes I noted the flaw.

Do not worry about the "swprint" functions, that was simply the remains of a trial and error process.

This isn't related to the problem, but with tkinter I'd recommend using the grid methods rather than the place and pack bs. You can weight columns and rows too to make the whole window scale nicely super ez

1 Like