使用Tkinter对象运行线程 [英] Running a thread with Tkinter object

查看:49
本文介绍了使用Tkinter对象运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

我从这个答案中偷偷地偷了一些代码,作为一些 tkinter 代码的基础:

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

下面的代码将其修改为具有 Queue Thread ,它们仅在按下按钮后运行.

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

Thread 通过 Queue mainloop 通信,该队列由对 root.after()的调用进行轮询.代码>

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()

mainloop()未被 Thread check_queue()进行的轮询所阻止.

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

这篇关于使用Tkinter对象运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆