使用Tkinter对象运行线程

时间:2019-05-13 17:44:09

标签: python multithreading function user-interface tkinter

当我按下按钮时,scan_open_ports开始工作,直到ip_list.curselection()行停止为止,此行会阻止函数的运行... 我想知道为什么以及如何解决? 谢谢

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 个答案:

答案 0 :(得分:0)

我从这个答案中偷偷窃了一些代码,以此作为一些tkinter代码的基础:How to align label, entry in tkinter

以下代码将其改编为具有QueueThread,它们仅在按下按钮后运行。

Thread通过mainloopQueue通讯,而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() 的呼叫进行轮询

mainloop()

Threadcheck_queue()所做的轮询都未阻止sub_list = [[1,2,3],[4,5,5], [2,63,6]] l1, l2, l3 = map(list, zip(*sub_list)) print(l1) print(l2) print(l3) # Output [1, 4, 2] [2, 5, 63] [3, 5, 6]