From 33331e829a3c0e4669d1d5e6e828921e258e8c8a Mon Sep 17 00:00:00 2001 From: Leon Teichroeb Date: Fri, 22 Oct 2021 21:11:58 +0200 Subject: [PATCH] Fixed ui_print, #6. Calls now processed in main thread. --- src/user_interface.py | 23 +++++++++++++++++++++++ src/utility.py | 12 ++++++------ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/user_interface.py b/src/user_interface.py index 8f97298..0af033a 100644 --- a/src/user_interface.py +++ b/src/user_interface.py @@ -1760,6 +1760,9 @@ class OutputConsole(Frame): def __init__(self, parent): Frame.__init__(self, parent, relief=SUNKEN, bd=1) + # Queue for messages to print when this class currently has main thread control + self.print_queue = Queue() + # configure Tkinter grid: self.grid_rowconfigure(ALL, weight=1) self.grid_columnconfigure(0, weight=1, minsize=60) # console needs to have a minimum width @@ -1773,3 +1776,23 @@ class OutputConsole(Frame): # link scrollbar to the console scrollbar.config(command=self.console.yview) self.console.config(yscrollcommand=scrollbar.set) + + # Start the main thread for printing queued messages + self.print_thread() + + def print_thread(self): + """ Continuous thread that checks if messages are present, and prints them if they are. """ + try: + while True: + msg = self.print_queue.get(block=False) + # print to console + self.console.insert(END, "\n" + msg) + except Empty: + pass + self.console.see(END) # scroll console to bottom + + # Print messages every 100 ms in the main Tkinter loop + self.after(100, self.print_thread) + + def put(self, message): + self.print_queue.put(message) diff --git a/src/utility.py b/src/utility.py index c1fdcde..fcdd592 100644 --- a/src/utility.py +++ b/src/utility.py @@ -7,9 +7,9 @@ def ui_print(*content): """prints text to built-in console, use exactly like normal print(). Requires the ui to be initialized""" output = " ".join([str(c) for c in content]) - if not g.exit_flag and g.app is not None: # application is still running --> output window is visible - output = "".join(("\n", output)) # begin new line each time - g.app.OutputConsole.console.insert(END, output) # print to console - g.app.OutputConsole.console.see(END) # scroll console to bottom - else: # if window is not open, do normal print - print(output) \ No newline at end of file + if not g.exit_flag and g.app is not None: + # application is still running --> output window is visible + g.app.OutputConsole.put(output) + else: + # if window is not open, do normal print + print(output)