这是一个粗略的演示,展示了如何将文本字符串打印到标签。请注意,长字符串不会被包装。如果需要,您必须自己通过插入 \n 换行符来包装字符串,或者使用 wraplength 选项,如 Label widget 文档中所述。或者,您可以使用 Text widget 而不是 Label 来显示文本。
我的test 函数模拟了“test.py”脚本中代码的操作。
import tkinter as tk
from time import sleep
# A dummy `test` function
def test():
# Delay in seconds
delay = 2.0
sleep(delay)
print_to_gui('Files currently transferring')
sleep(delay)
print_to_gui('Currently merging all pdfs')
sleep(delay)
print_to_gui('PDFs have been merged')
sleep(delay)
print_to_gui('Finished!\nYou can click the "Run test"\n'
'button to run the test again.')
# Display a string in `out_label`
def print_to_gui(text_string):
out_label.config(text=text_string)
# Force the GUI to update
top.update()
# Build the GUI
top = tk.Tk()
top.wm_title("testest")
top.minsize(width=300, height=150)
top.maxsize(width=300, height=150)
b = tk.Button(top, text='Run test', command=test)
b.config(width=15, height=1)
b.pack()
# A Label to display output from the `test` function
out_label = tk.Label(text='Click button to start')
out_label.pack()
top.mainloop()
请注意,我们通常不在 GUI 程序中调用 time.sleep,因为它会导致整个程序在睡眠发生时冻结。我在这里用它来模拟当你的真实代码执行它的处理时会发生的阻塞延迟。
在不阻止正常 GUI 处理的 Tkinter 程序中进行延迟的常用方法是使用.after method。
您会注意到我用import tkinter as tk 替换了您的from tkinter import *。这意味着我们需要输入例如tk.Label 而不是Label,但这使代码更易于阅读,因为我们现在知道所有不同名称的来源。这也意味着我们不会用 tkinter 定义的所有名称来淹没我们的命名空间。 import tkinter as tk 只是在命名空间中添加了 1 个名称,from tkinter import * 在当前版本中添加了 136 个名称。请参阅Why is “import *” bad? 了解有关此重要主题的更多信息。
这是一个稍微花哨的示例,它将新文本附加到当前的标签文本中,并带有自动换行。它还有一个函数clear_label 可以从标签中删除所有文本。它不是直接将文本存储在标签中,而是使用StringVar。这使得访问旧文本更容易,以便我们可以附加到它。
import tkinter as tk
from time import sleep
# A Dummy `test` function
def test():
# Delay in seconds
delay = 1.0
clear_label()
print_to_label('Files currently transferring')
sleep(delay)
print_to_label('Currently merging all pdfs')
sleep(delay)
print_to_label('PDFs have been merged')
sleep(delay)
print_to_label('\nFinished!\nYou can click the "Run test" '
'button to run the test again. '
'This is a very long string to show off word wrapping.'
)
# Append `text_string` to `label_text`, which is displayed in `out_label`
def print_to_label(text_string):
label_text.set(label_text.get() + '\n' + text_string)
# Force the GUI to update
top.update()
def clear_label():
label_text.set('')
top.update()
# Build the GUI
top = tk.Tk()
top.wm_title("testest")
top.minsize(width=300, height=150)
top.maxsize(width=300, height=350)
b = tk.Button(top, text='Run test', command=test)
b.config(width=15, height=1)
b.pack()
# A Label to display output from the `test` function
label_text = tk.StringVar()
out_label = tk.Label(textvariable=label_text, wraplength=250)
label_text.set('Click button to start')
out_label.pack()
top.mainloop()