python的tkinter進度條的實現

請看程序運行過程:

進度條滿了之後,能實現自動清理,這是因爲加上了自動清理的代碼,如果不需要,可以去掉。

源代碼:

import tkinter as tk
import time

# 創建主窗口
window = tk.Tk()
window.title('進度條')
window.geometry('630x150')

# 設置下載進度條
tk.Label(window, text='下載進度:', ).place(x=50, y=60)
canvas = tk.Canvas(window, width=465, height=22, bg="white")
canvas.place(x=110, y=60)

# 顯示下載進度
def progress():
    # 填充進度條
    fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="green")
    x = 500  # 未知變量,可更改
    n = 465 / x  # 465是矩形填充滿的次數
    for i in range(x):
        n = n + 465 / x
        canvas.coords(fill_line, (0, 0, n, 60))
        window.update()
        time.sleep(0.02)  # 控制進度條流動的速度

    # 清空進度條
    fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill="white")
    x = 500  # 未知變量,可更改
    n = 465 / x  # 465是矩形填充滿的次數

    for t in range(x):
        n = n + 465 / x
        # 以矩形的長度作爲變量值更新
        canvas.coords(fill_line, (0, 0, n, 60))
        window.update()
        time.sleep(0)  # 時間爲0,即飛速清空進度條

btn_download = tk.Button(window, text='啓動進度條', command=progress)
btn_download.place(x=400, y=105)

window.mainloop()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章