Home > Blockchain >  How to handle mainloop and serve_forever socket server together in if __name__ == '__main__
How to handle mainloop and serve_forever socket server together in if __name__ == '__main__

Time:01-22

I am using Tkinter which has a QRcode generate button. I want to create a QRcode based on the provided URL and if I click the QRcode generate button then it will generate a QRcode and the URL will be active forever. The code I tried so far.

generate_button = tk.Button(my_w,font=22,text='Generate QR code', command=lambda:my_generate())
generate_button.place(relx=0.2, rely=0.5, anchor=CENTER)

qrcode_label=tk.Label(my_w)
qrcode_label.place(relx=0.6, rely=0.5, anchor=CENTER)

link ='http://192.x.x.x:8010'
PORT = 8010

def my_generate():
    global my_img
    my_qr = pyqrcode.create(link) 
    my_qr = my_qr.xbm(scale=10)
    my_img=tk.BitmapImage(data=my_qr)
    qrcode_label.config(image=my_img)

So far everything is cool. Now if I try to activate the server beside the main Tkinter window, seems both two loops are going to conflict and the application gets crashed.

if __name__ == '__main__':
    Handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", PORT), Handler)
    print("serving at port", PORT)
    httpd.serve_forever()
    my_w.mainloop()

Tried some ways but nothing helps me so far.

CodePudding user response:

To avoid the conflict between the Tkinter mainloop and the server's loop, you can use the threading module to run the server on a separate thread. You can create a new thread and run the server's serve_forever() method on that thread. Here is an example of how you can do this:

import threading

if __name__ == '__main__':
    my_w.mainloop()
    server_thread = threading.Thread(target=serve_forever)
    server_thread.start()

def serve_forever():
    Handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", PORT), Handler)
    print("serving at port", PORT)
    httpd.serve_forever()

This way, the Tkinter mainloop and the server's loop will run in parallel and won't conflict with each other.

  • Related