python 无法从线程更新Tkinter标签

nafvub8i  于 2023-02-28  发布在  Python
关注(0)|答案(1)|浏览(216)

我尝试从Thread更新标签的文本,但是没有成功。下面是代码的一个示例

def search_callback():
    class Holder(object):
        done = False

    holder = Holder()
    t = threading.Thread(target=animate, args=(holder,))
    t.start()
    #long process here
    holder.done = True   # inform thread long process is finished

def animate(holder):
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if holder.done:
            break
        print('\rRecherche ' + c)   # This work!
        label_wait.configure(text='\rRecherche ' + c)  # this doesn't work nothing appear in my label
        time.sleep(0.5)
    label_wait.configure(text='\rTerminé!     ')
    print('\rTerminé!  ')

但是我不明白为什么label_wait.configure不工作,print也工作得很好。
我试过在我的线程中使用after方法,但它没有改变。

nhaq1z21

nhaq1z211#

线程,但它不工作
不用担心Thread

  • False更改为holder.done = False
  • 删除了label_wait.configure(text='\rTerminé! ')print()

'
片段:

import tkinter as tk
import itertools
import time
import threading

root = tk.Tk()

def search_callback():
    class Holder(object):
        done = False

    holder = Holder()
    t = threading.Thread(target=animate, args=(holder,))
    t.start()
    #long process here
    holder.done = False   # inform thread long process is finished

def animate(holder):
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if holder.done:
            break
        print('f\rRecherche {c}')   # This work!
        label_wait.configure(text=f'\rRecherche {c}')  # this doesn't work nothing appear in my label
        time.sleep(0.5)
    
label_wait = tk.Label(root)
label_wait.pack()
search_callback()
root.mainloop()

截图:

相关问题