我已经为我的 python 脚本创建了一个 tkinter GUI。当我运行脚本时,我希望在 GUI 窗口的一个标签小部件中有一个动态字符串,它将显示:
“工作。” 然后: “在职的..” 然后 “正在工作……”
然后从“工作”开始。再次直到脚本完成。
(其实我更喜欢这个区域的进度条)
这可能吗?
最佳答案
我写了两个简单的脚本来帮助演示如何做你想做的事。第一个是使用标签:
import tkinter as tk
root = tk.Tk()
status = tk.Label(root, text="Working")
status.grid()
def update_status():
# Get the current message
current_status = status["text"]
# If the message is "Working...", start over with "Working"
if current_status.endswith("..."): current_status = "Working"
# If not, then just add a "." on the end
else: current_status += "."
# Update the message
status["text"] = current_status
# After 1 second, update the status
root.after(1000, update_status)
# Launch the status message after 1 millisecond (when the window is loaded)
root.after(1, update_status)
root.mainloop()
下一个是使用进度条:
import tkinter as tk
# You will need the ttk module for this
from tkinter import ttk
def update_status(step):
# Step here is how much to increment the progressbar by.
# It is in relation to the progressbar's length.
# Since I made the length 100 and I am increasing by 10 each time,
# there will be 10 times it increases before it restarts
progress.step(step)
# You can call 'update_status' whenever you want in your script
# to increase the progressbar by whatever amount you want.
root.after(1000, lambda: update_status(10))
root = tk.Tk()
progress = ttk.Progressbar(root, length=100)
progress.pack()
progress.after(1, lambda: update_status(10))
root.mainloop()
但是请注意,我不能对进度条脚本做太多事情,因为进度条有点棘手,需要根据您的脚本进行精确定制。我写它只是为了对这个主题有所了解。不过,我回答的主要部分是标签脚本。
关于Python:当函数在后台运行时,是否可以创建一个具有动态字符串的 tkinter 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18047636/