Skip to content Skip to sidebar Skip to footer

Running A Thread With Tkinter Object

When I push the button the scan_open_ports start working until the line ip_list.curselection() where it stops, this line blocks the running of the function... I wanted to know why

Solution 1:

I have shamelessly stolen some code from this answer, just as a basis for some tkinter code: How to align label, entry in tkinter

The following code adapts this to have a Queue and a Thread which only runs after a button press.

The Thread communicates back to the mainloop through the Queue which is polled by calls to root.after()

from tkinter import *
from threading import Thread
from queue import Queue
from time import sleep
from random import randint

root = Tk()

root.geometry("583x591+468+158")
root.title("NOKIA _ANSI Performance")
root.configure(borderwidth="1")
root.configure(relief="sunken")
root.configure(background="#dbd8d7")
root.configure(cursor="arrow")
root.configure(highlightbackground="#d9d9d9")
root.configure(highlightcolor="black")

Label3 = Label(root)
Label3.configure(text='''Device  IP Address :''')
Label3.pack()
Label5 = Label(root)
Label5.configure(text='''Username :''')
Label5.pack()

Entry5 = Entry(root)
Entry5.pack()
th = None
q = Queue()

def run_me(q):
    sleep(5)
    q.put(randint(1, 99))

def check_queue():
    if not q.empty():
        item = q.get()
        Label5.configure(text=str(item))
    root.after(200, check_queue)

def do_thread():
    global th
    th = Thread(target=run_me, args=(q,))
    th.start()

Button1 = Button(root)
Button1.configure(pady="0")
Button1.configure(text='''NEXT''')
Button1.configure(command=do_thread)
Button1.pack()
root.after(200, check_queue)
mainloop()

The mainloop() is not blocked either by the Thread nor by the polling that check_queue() does.


Post a Comment for "Running A Thread With Tkinter Object"