如何更新画布“进度”栏?

2024-09-30 06:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想不出来。我还在循环中尝试了after()。目标是通过使用画布(和更新标签)创建进度条。问题是,整个窗口在“循环”之后生成

from tkinter import *
import time

root = Tk()
root.geometry("350x350")
root.maxsize(350,350)
root.minsize(350, 350)
root.attributes("-transparentcolor", "red")

can = Canvas(root, bg="red", highlightthickness=0)
can.place(relwidth=1, relheight=1)

ext = 3.59
for x in range(100):
    can.create_arc(10, 10, 340, 340, extent=ext, fill="#a7bee6", width=0)
    #time.sleep(0.1)
    ext += 3.59
can.create_oval(30, 30, 320, 320, fill="red", width=0)
can.create_oval(50, 50, 300, 300, fill="#1f1f1f", width=0)

lbl = Label(can, bg="#1f1f1f", fg="#a7bee6", text="%", font=("Consolas", 30))
lbl.pack(pady=150)

for x in range(101):
    lbl.configure(text=f"{x}%")
    time.sleep(0.1)


mainloop()

Tags: inimportfortimecreaterangeredroot
1条回答
网友
1楼 · 发布于 2024-09-30 06:29:33

这应该可以通过使用after(ms,func)实现,只需从主块中删除所有执行增量的代码,并将其移动到函数中,然后只需使用after,如:

count = 0
def progress():
    global ext, count
    if count < 100: # Same as doing 100 loops
        can.create_arc(10, 10, 340, 340, extent=ext, fill="#a7bee6", width=0)
        ext += 3.59
        count += 1
        lbl.configure(text=f"{count}%") # Update label 
        root.after(100,progress) # Same as time.sleep(0.1)

progress() # Call the function initially

当您使用time.sleep()时,它会阻止mainloop处理或更新事件,因此GUI将保持冻结状态,直到time.sleep()或任何其他循环完成


虽然我没有讨论progressbar的功能,但似乎在最后还有一点地方可以覆盖,以显示100%的圆。我认为将ext增加3.60可以解决这个问题(ext+=3.60

相关问题 更多 >

    热门问题