【发布时间】:2018-09-20 02:49:31
【问题描述】:
我正在使用 tkinter 开发一个 GUI 来管理数据库中的图像(导入文件、加载文件、查询......)
当扫描新目录及其子目录以查找要放入数据库的新图像时,会启动专用 GUI: 它由一个 Text 小部件组成,其中打印了当前分析的目录的名称,以及一个显示扫描进度的进度条。 当我单独调用此 GUI 时,只要我在每次更改进度条后使用 update(),进度条就会更新并正确进行。另一方面, 即使我不使用更新,文本小部件也会正确更新。
但是,当我从主 GUI 调用进度条时,进度条不会按应有的方式更新,而 Text 小部件会正确更新。
希望有人能帮忙!
以下是进度条 GUI 的代码。我正在使用 Python 3.6。
from tkinter.filedialog import *
from tkinter.ttk import *
class ScanDirectoryForJPG(Tk):
"""
Inherited from the Tk class
"""
def __init__(self, parent, Path=None):
Tk.__init__(self, parent)
self.parent = parent
self.PathDicom = Path
if self.Path == None:
self.Path = askdirectory(title='Select a directory to scan')
self.title('Scan {} for JPG files'.format(self.Path))
self.status_string = 'Scanning the content of {} folder\n'.format(self.Path)
self.initialize_gui()
self.scan_directory()
def initialize_gui(self):
# Style
self.style = Style()
self.style.theme_use('vista')
# Main window
self.grid()
self.grid_columnconfigure([0], weight=1)
self.grid_rowconfigure([0], weight=1)
# Status
self.status_label = Text(self)
self.status_label.grid(row=0, column=0, sticky='NSEW')
self.status_label.insert(END, 'Looking for JPG files in {}\n'.format(self.Path))
# Progress Bar
self.p = DoubleVar()
self.progress_bar = Progressbar(self, orient='horizontal', mode='determinate', variable=self.p, maximum=100)
self.p.set(0)
self.progress_bar.grid(row=1, column=0, rowspan=1, sticky='EW')
def scan_directory(self):
"""
"""
number_of_files = sum([len(files) for r, d, files in os.walk(self.Path)])
count = 0
for dirName, subdirList, fileList in os.walk(self.Path):
self.status_label.insert(END, '\t-exploring: {}\n'.format(dirName))
self.update()
for filename in fileList:
count += 1
value = count / number_of_files * self.progress_bar['maximum']
if value >= (self.progress_bar['value'] + 1):
# update the progress bar only when its value is increased by at least 1 (avoid too much updates of the progressbar)
self.p.set(self.progress_bar['value'] + 1)
self.update()
file = os.path.join(dirName, filename)
# if the file is a JPG, load it into the database
# ...
# ...
# ..
self.status_label.insert(END, 'FINISH\n')
self.update()
if __name__ == '__main__':
app = ScanDirectoryForJPG(None, Path='D:\Data\Test')
app.mainloop()
print('App closed')
【问题讨论】:
-
您的问题似乎可以归结为:“为什么从主 GUI 调用进度条时没有更新?”当你说“打电话”时,你到底是什么意思?我怀疑您的意思是“呼叫班级”,这意味着
Tk.__init__()被称为结果。如果它发生在程序的另一部分也已经调用它之后,这可能就是问题所在,因为您不能同时运行两个Tk实例——它们不能很好地协同工作。不过,有有种方法可以创建多个顶级窗口,而不是您[可能] 正在这样做的方式。 -
是的,你是对的,我的意思是给班级打电话。我在一些论坛上看到有人使用线程和队列,但对于我的水平来说太复杂了。所以看来我被我的问题困住了?但是为什么 Text 小部件会正确更新呢?
-
创建第二个窗口的常用方法是创建(调用)
tkinter.TopLevel的实例。这样做需要不从Tk类派生ScanDirectoryForJPG类。这实际上可能相当容易做到。如果您编辑帖子并提供 Minimal, Complete, and Verifiable example 来演示问题,那么有人可能会向您展示如何执行此操作。
标签: python python-3.x tkinter ttk