更新帖子

时间:2017-11-13 17:17:20

标签: multithreading python-2.7 tkinter

我有一个Python代码,我在其中创建了一个进度条。 Tkinter环境在带有进度条的Gui函数中创建,并作为线程启动。然后在另一个线程中我计算进度条必须具有的值,但问题是我不知道如何使用进度条的新值更新Gui线程。这是我的代码:

import tkinter as tk
from tkinter import ttk
import thread

def Gui(): 
   root = tk.Tk()
   root.geometry('450x450')
   root.title('Hanix Downloader')

   button1 = tk.Button(root, text='Salir', width=25,command=root.destroy)
   button1.pack()

   s = ttk.Style()
   s.theme_use('clam')
   s.configure("green.Horizontal.TProgressbar", foreground='green', background='green')

   mpb = ttk.Progressbar(root,style="green.Horizontal.TProgressbar",orient ="horizontal",length = 200, mode ="determinate")
   mpb.pack()
   mpb["maximum"] = 3620
   mpb["value"] = 1000

   root.mainloop()

def main():
while True:
    #Calculate the new value of the progress bar.
    mpb["value"] = 100 #Does not work
    root.update_idletasks()#Does not work
    #Do some other tasks.


if __name__ == '__main__':
thread.start_new_thread( Gui,() )
thread.start_new_thread( main,() )

我得到的错误是mpb和root不存在。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您应该收到错误,因为mpbroot是仅存在于Gui但不存在于main中的局部变量。您必须使用global通知两个函数都使用全局变量 - 然后main将有权访问mpb中创建的Gui

我还在time.sleep(1)之前添加了while True:,因为有时main可能会比Gui更快开始,但可能找不到mpb(因为Gui没有时间创建进度条)

import tkinter as tk
from tkinter import ttk
import _thread
import time

def Gui():
   global root, mpb

   root = tk.Tk()

   button1 = tk.Button(root, text='Exit', command=root.destroy)
   button1.pack()

   mpb = ttk.Progressbar(root, mode="determinate")
   mpb.pack()

   mpb["maximum"] = 3000
   mpb["value"] = 1000

   root.mainloop()


def main():
    global root, mpb

    time.sleep(1)

    while True:
        mpb["value"] += 100
        #root.update_idletasks() # works without it

        #Do some other tasks.
        time.sleep(0.2)


if __name__ == '__main__':
    _thread.start_new_thread(Gui, ())
    _thread.start_new_thread(main, ())

在Python 3.6.2,Linux Mint 18.2

上测试

编辑:更准确地说:您只需global Gui,因为它会为变量分配值 root = ...mpb = ...

相关问题