正确完成Tkinter线程(有或没有队列)

2024-06-02 04:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个更高级的代码,但都是这个简单的示例:

from Tkinter import *
import time

def destroyPrint():
    global printOut
    try:
        printOut.destroy()
    except:
        pass


def sendData():
    global new
    global printOut
    for i in range(6):
        destroyPrint()
        time.sleep(1)
        printOut=Label(new,text=i,font=('arial',15,'bold'))
        printOut.place(x=300,y=500)


def newWindow():
    global new
    print("ok")
    new=Toplevel()
    new.minsize(800,600)
    functionButton=Button(new,text="Send me",width=20,height=20, command=sendData)
    functionButton.place(x=300,y=150)


main = Tk()
main.minsize(800, 600)
menu=Button(main,text="Send data",width=20,height=20, command=newWindow)
menu.place(x=300,y=150)
mainloop()

在这个简单的例子中,我想启动sendData函数,它将在每次循环迭代中相应地更新printOut标签。我们都知道它不会,并且它会挂起,直到函数完成,并打印最后一个数字(5)。在

我尝试了无数线程和排队的例子,但我失败得很惨。 请简单说明一下这个例子,当你在一个函数中有Tkinter元素需要在另一个线程中执行时,如何正确地执行线程。在

我真的很沮丧,我花了两天在这一步。。。在


Tags: 函数textimportnewtimemaintkinterdef
1条回答
网友
1楼 · 发布于 2024-06-02 04:45:26

必须添加update_idletasks()才能更新标签。与其销毁和创建,只需更新文本,并在Tkinter中使用after()而不是sleep,因为它会生成一个新的进程时间。睡觉()睡眠时挂起程序。在

from Tkinter import *
import time

def sendData():
    global new
    ##global printOut
    printOut=Label(new,text="0",font=('arial',15,'bold'))
    printOut.place(x=300,y=500)
    for x in range(6):
        ##destroyPrint()
        printOut.config(text=str(x))
        new.update_idletasks()
        time.sleep(1)

def newWindow():
    global new
    print("ok")
    new=Toplevel()
    new.minsize(800,600)
    functionButton=Button(new,text="Send me",width=20,
                  height=20, command=sendData)
    functionButton.place(x=300,y=150)


main = Tk()
main.minsize(800, 600)
menu=Button(main,text="Send data",width=20,height=20, command=newWindow)
menu.place(x=300,y=150)
main.mainloop()

相关问题 更多 >