tkinter:progressbar,指示上载文件的状态

jq6vz3qz  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(232)

嗨,我想在我的tkinter gui中有一个进度条,它提供关于文件加载状态的视觉提示。这是我的代码,但当我启动它的应用程序只是卡住,无法工作(我必须关闭它的力量)。

def start():
    file = filedialog.askopenfilename(filetypes =(("Text File", "*.txt"),("All Files","*.*")), title = "Select") 
    filesize = os.path.getsize(file)

    with open(file, "r", encoding='utf-8') as f:
        for i in range(os.path.getsize(file)):
            progressbar["value"] = 5      
            progressbar["maximum"] = filesize
            label.config(text=str(progressbar["value"]) + "%")          
            root.update_idletasks()
            time.sleep(1) 

label = ttk.Label(root, text="00%")
label.pack()

button_prg = Button(root, text="progress", command=start)
button_prg.pack()

progressbar = ttk.Progressbar(root, orient="horizontal", length=100,  mode='determinate')
progressbar.pack()

还有没有办法调整酒吧的高度?因为我想把它放在框架底部的状态栏中。谢谢大家!!

yuvru6vn

yuvru6vn1#

你想要什么,我不太明白。。但这里是你应该拥有的:

import time
import os
from tkinter import * #importing * is a very bad habit!
from tkinter import ttk
from tkinter import filedialog
def start():
    file = filedialog.askopenfilename(filetypes =(("Text File", "*.txt"),("All Files","*.*")), title = "Select") 
    filesize = os.path.getsize(file)

    with open(file, "r", encoding='utf-8') as f:
        for i in range(os.path.getsize(file)):
            progressbar["value"] = progressbar["value"]+1
            progressbar["maximum"] = filesize
            label.config(text=str(int(progressbar["value"]/os.path.getsize(file)*100)) + "%")          
            root.update_idletasks()
            #time.sleep(1) 

root = Tk()

label = ttk.Label(root, text="00%")
label.pack()

button_prg = Button(root, text="progress", command=start)
button_prg.pack()

progressbar = ttk.Progressbar(root, orient="horizontal", length=100,  mode='determinate')
progressbar.pack()
root.mainloop()

顺便说一句,文件大小是有限制的。。这是400kb。。我无法加载任何大于400kb的文件!

相关问题