我試圖在Python和Gtk3中使用進度條,但它沒有得到更新。我已閱讀this文檔和這個論壇中的一些問題(主要針對pygtk),我真的不明白!Gtk.ProgressBar不能在Python中工作
我爲測試目的只做了一個代碼。當你點擊一個按鈕時,它會遞歸地讀取一個目錄的內容。我的意圖是在閱讀所有這些文件時使用進度條。
這是整個代碼:
import os
from gi.repository import Gtk
class MyWindow(Gtk.Window):
"""Progress Bar"""
def __init__(self):
Gtk.Window.__init__(self, title='Progress Bar')
self.set_default_size(300, 75)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_border_width(10)
# read dir contents
mydir = 'Documents'
home_path = os.environ.get('HOME')
dir_path = os.path.join(home_path, mydir)
self.dir_files_list(dir_path)
# create a grid
self.grid = Gtk.Grid(column_homogeneous=True, row_homogeneous=True,
column_spacing=10, row_spacing=10)
self.add(self.grid)
# create a progress bar
self.progressbar = Gtk.ProgressBar()
self.grid.add(self.progressbar)
# create a button
self.button = Gtk.Button(stock=Gtk.STOCK_APPLY)
self.button.connect('clicked', self.on_button_pressed)
self.grid.attach(self.button, 0, 1, 1, 1)
# function to read the dir contents
def dir_files_list(self, dir_path):
self.dir_list = []
for root, dirs, files in os.walk(dir_path):
for fn in files:
f = os.path.join(root, fn)
self.dir_list.append(f)
# function to update the progressbar
def on_button_pressed(self, widget):
self.progressbar.set_fraction(0.0)
frac = 1.0/len(self.dir_list)
for f in self.dir_list:
new_val = self.progressbar.get_fraction() + frac
print new_val, f
self.progressbar.set_fraction(new_val)
return True
def main():
"""Show the window"""
win = MyWindow()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()
return 0
if __name__ == '__main__':
main()
從一個更有經驗的程序員任何幫助表示讚賞!
非常感謝。現在,您可以解釋一下Gtk +和線程,但我不確定我是否能夠在我的程序中實現此功能......至少我會去嘗試...我感謝您爲解釋隱藏在我的問題之外的內容而付出的努力。 – skytux 2013-04-10 19:45:15
我更新了答案,檢查PyGObject版本:https://gist.github.com/carlos-jenkins/5358445 – Havok 2013-04-10 21:20:09
非常感謝您的時間。我要去看看那個版本。格拉西亞斯! – skytux 2013-04-10 22:57:33