首页 > 解决方案 > 使用 stringvar 的 Python 标签

问题描述

我正在尝试将文本字符串附加到 Tkinter 中的标签。

我得到“label_text”没有定义。我已将标签文本分配给 StringVar 但仍然收到“名称标签文本未定义”

我感谢任何帮助摆脱错误。

#!/usr/bin/python3
from tkinter import *
import time

def test():
    delay = 3.0
    time.sleep(delay)
    print_to_gui('Files currently transferring')
    time.sleep(delay)
    print_to_gui('Currently merging all pdfs')

# Append `text_string` to `label_text`, which is displayed in `out_label`
def print_to_gui(text_string):
    label_text.set(label_text.get() + '\n' + text_string)
    # Force the GUI to update
    Root.update()

def clear_label():
    label_text.set('')
    Root.update()

def main():
    Root = Tk()
    label_text = StringVar()
    Root.wm_title("testest")
    Root.minsize(width=300, height=150)
    Root.maxsize(width=300, height=150)
    b = Button(Root, text='Run test', command = test)
    b.config(width=15, height=1)
    b.pack()
    # A Label to display output from the `test` function
    out_label = Label(Root, textvariable=label_text, wraplength=250, bg='red')
    label_text.set('Click button to start')
    out_label.pack()
    Root.mainloop()

if __name__ == "__main__":
    main()

标签: pythonpython-3.xtkinter

解决方案


推荐阅读