Tkinter标签文本未更新,标签可见且文本值是最新的

时间:2019-07-14 08:27:46

标签: python tkinter text label

当尝试通过按一下按钮在tkinter窗口上显示文本超时时,标签无法正确更新。在测试了多种不同的场景之后,标签被分类为可见,其文本值正确,该函数本身无需按下按钮即可工作,无论使用包,网格还是放置结果均相同。无论标签如何更新,它都不会在屏幕上显示,只有在按钮调用该功能时才显示。当按下按钮时,它将遍历该功能,并打印出所有内容,因此按钮本身也可以使用。下面的代码:

    def label_change(self, text):
    """ Repeats f|char_show (with a pause) until <text> equals the label text.

    Parameters:
        text (str): The text displayed in the label.
    """
    if self.last_txt == text:
        pass

    def char_show():
        """ Adds the next single character of <text> to the label text.

        Curtosy of Hritik Bhat on:
        stackoverflow.com/questions/56684556/how-to-have-variable-text-in-a-label-in-tkinter
        """

        if self.label_store == "":
            self.label_index = 0

        self.label_store += text[self.label_index]
        print(self.label_index)
        self.label_index += 1

        self.display.place_forget()
        self.display.config(text=self.label_store)
        self.display.update()
        self.display.place()

        print(self.display.cget("text"))
        self.display.update_idletasks()
        self.label_change(self.txt)

1 个答案:

答案 0 :(得分:0)

如果要延迟添加字符,则可以使用root.after(time_ms, function_name)来延迟执行函数。这不会停止mainloop(),也不需要update()和`update_idletask()

import tkinter as tk

def start():
    global label_index

    # add next char to label
    display['text'] += text[label_index]
    label_index += 1

    # check if there is need to run it again
    if label_index < len(text):
        # run again after 200ms
        root.after(200, start)

# ---

text = 'Hello World'
label_index = 0

root = tk.Tk()

display = tk.Label(root)
display.pack()

button = tk.Button(root, text="Start", command=start)
button.pack()

root.mainloop()

编辑:此版本在更新标签时会阻止按钮。再次启动动画时,它还会重置设置。

将tkinter导入为tk

def add_char():
    global label_index
    global running

    # add next char to label
    display['text'] += text[label_index]
    label_index += 1

    # check if there is need to run it again
    if label_index < len(text):
        # run again after 200ms
        root.after(200, add_char)
    else:
        # unblock button after end
        running = False

def start():
    global label_index
    global running

    # check if animation is running
    if not running:
        # block button
        running = True

        # reset settings
        display['text'] = ''
        label_index = 0

        # run animation
        add_char()

# ---

text = 'Hello World'
label_index = 0
running = False

root = tk.Tk()

display = tk.Label(root)
display.pack()

button = tk.Button(root, text="Start", command=start)
button.pack()

root.mainloop()