I want to create a large text upon Tkinter
menu command and provide visual support by a progress bar. Although the progress bar is meant to start before the subsequent time-consuming loop, the progress bar shows up only after the large text was created and displayed.
def menu_bar(self):
self.create_menu.add_command(label="Create large file",
command=self.create_large_file)
def create_large_file(self):
self.progressbar = ttk.Progressbar(self.master, mode='indeterminate')
self.progressbar.pack()
self.progressbar.start()
self.text.delete(1.0, 'end')
self.file_content = []
i = 0
while i < 2000000:
line = lfd.input_string
self.file_content.append(line + "\n")
i += 1
self.file_content = ''.join(self.file_content)
self.text.insert(1.0, self.file_content)
Here's another considerably simpler solution that doesn't require mixing Tkinter and multi-threading. To use it requires the ability to call the progressbar widget's
update_idletasks()
method multiple times during the time-consuming function.I think the problem is that the time-consuming loop is preventing the
tkinter
event loop,mainloop()
, from running. In other words, when your work intensive function runs in the same thread as the GUI, it interferes with it by hogging the interpreter.To prevent this you can use a secondary Thread to run your function and run the GUI and its progressbar in the main thread. To give you and idea of how to do this, here's a simple example I derived from code in a another (unrelated) progressbar question to show how easily something like that can be done. Note: It's generally recommended that secondary threads not be given direct access to the main thread's
tkinter
objects.