Robert Altman
Robert Altman

Reputation: 181

Tkinter Threading causing UI freeze

I've searched this site (and others) up and down but I can't seem to find the right solution.

I have a client program that connects to a server and automatically sends a message every few seconds, as well as on user command. I'm using multiple threads for this. Enter Tkinter: Once I hit the 'Connect' button, my UI freezes, either until the connection attempt times out or until the end of time, should the client connect to the server.

I've tried calling the thread from the button's command parameter, from inside the main loop, and outside the main loop. I've tried putting the main loop in a thread and then creating a new thread for the connection from there. Nothing seems to be working...the UI continues to hang.

class EventSim(Frame):

    def __init__(self, parent):
        self.queue = Queue
        Frame.__init__(self, parent)

        self.parent = parent   

    def initUI(self,IP_Address,Port_Number,Events_Directory):
    #...
    self.Con_Button = Button(frame7,text='Connect', command = lambda:
        self.connect(IP_Text.get(),Port_Text.get(),))

    def connect(self,IP,Port):
        ConnectionThread = Thread(eventsim.con_thread(IP,Port))
        ConnectionThread.start()


def main():
root = Tk()
root.geometry("300x310+750+300")
Sim = EventSim(root)
eventsim.readconfig()
Sim.initUI(eventsim.ipa,eventsim.portnum,eventsim.event_dir)
root.mainloop()

Upvotes: 0

Views: 1163

Answers (1)

acw1668
acw1668

Reputation: 46669

You pass the result of eventsim.con_thread(IP,Port) to Thread(...) function, so it will wait until the execution of eventsim.con_thread(...) completes. Try changing:

def connect(self, IP, Port):
    ConnectionThread = Thread(eventsim.con_thread(IP,Port))
    ConnectionThread.start()

to:

def connect(self, IP, Port):
    ConnectionThread = Thread(target=lambda ip=IP, port=Port: eventsim.con_thread(ip,port))
    ConnectionThread.start()

Upvotes: 2

Related Questions