Running a thread with Tkinter object

流过昼夜 提交于 2021-02-05 09:46:39

问题


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 and how to fix that? Thanks

def scan_open_ports():
    #long runtime function
    print "Asdasd\"
    ip_list.curselection()
def thr_open_ports():
    threading.Thread(target=scan_open_ports).start()
ip_list = Listbox()
scan_ports = Button(window, text="Scan Open Ports", command= thr_open_ports, height = 10, width = 20)

回答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.



来源:https://stackoverflow.com/questions/56117419/running-a-thread-with-tkinter-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!