Home > Back-end >  How to prevent my server Tkinter app from freezing when clicking a button?
How to prevent my server Tkinter app from freezing when clicking a button?

Time:09-23

I'm a newcomer to socket programming and currently trying to create a really simple GUI app that asks server to connect with a single client by clicking a button.

The problem is, the app always freezes and only turns back to normal after it has already been connected to the client. I have done some research and am currently assuming that the blocking socket causes the issue. Is there any other reason than this and how can I solve it?

Here is my server.py:

from tkinter import *
from tkinter import ttk
from socket import * 
                                         
def connect(): 
    global connectionSocket 
 
    serverPort = 12345
    socketServer = socket(AF_INET, SOCK_STREAM)
    socketServer.bind(('',serverPort))
    socketServer.listen(1) 
    print('The server is ready to receive') 
    
    while True:    
        connectionSocket, addr = socketServer.accept()
        connectionSocket.close()
        break
             
root = Tk()
root.title("Server App")
    
button_connect = ttk.Button(root,text = 'Connect', width = 20, command = connect)

button_connect.grid(row = 0, column = 0) 
            
root.mainloop() 

CodePudding user response:

Use Threading to prevent your app from freezing and your connect function will run like parallelly to tkinter app

from tkinter import *
from tkinter import ttk
from socket import *
import threading
                                         
def connect(): 
    global connectionSocket 
 
    serverPort = 12345
    socketServer = socket(AF_INET, SOCK_STREAM)
    socketServer.bind(('',serverPort))
    socketServer.listen(1) 
    print('The server is ready to receive') 
    
    while True:    
        connectionSocket, addr = socketServer.accept()
        connectionSocket.close()
        break
    s=0

def connectit():
    global s
    if (s==0):
        t = threading.Thread(target=connect)
        t.start()
        s = 1
s = 0
root = Tk()
root.title("Server App")
    
button_connect = ttk.Button(root,text = 'Connect', width = 20, command = connectit)

button_connect.grid(row = 0, column = 0) 
            
root.mainloop()

You can study about Threading from her

https://realpython.com/intro-to-python-threading/

You can also use Multiprocessing library instead of threading

https://www.geeksforgeeks.org/multiprocessing-python-set-1/

  • Related