Python:当函数在后台运行时,是否可以创建一个具有动态字符串的 tkinter 标签?

标签 python user-interface tkinter

我已经为我的 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/

相关文章:

python - Celery 如何处理链内的任务失败?

c++ - 我如何在wxWidgets中通过id获取一个widget?

algorithm - Line(x1,y1,x2,y2) 只需要使用 PutPixel(x,y) 示例吗?

python - 如果有很多小部件,则使按钮向左对齐

python - 用 Python 听 USB 键盘

python - Python 中的线程和多处理操作系统模块

javascript - web2py CRUD.create() 表单中的字段表示

python - 限制wxpython中wxListCtrl的大小

python - 确定当前在顶部的 tkinter 窗口

python - TKinter - 如何从 Entry() 添加两个数字