0

I'm new to tkinter and I'm trying to figure out the best practice for updating the UI based on some non ui logic running in a different thread.

For example, right now I have a button that triggers a creation of a thread, where it's run() method handles some heavy logic. During that logic, I want to be able to update the UI, like enabling/disabling some buttons.

I thought of creating an events queue, pass it to the running logic thread that will put events in that queue, and another thread within the UI context will pull events from that queue and update the UI accordingly.

I've been looking here, but it looks like those events are meant to trigger some actions based on stuff going on in the UI, I actually need the opposite.

  • This is not a proper question. Your question should include minimalistic code that examples a reproducible error, and we would help you fix that error. You are basically asking us to design a back-end for you or at the very least explain to you how. That is not-at-all what this site is for. – OneMadGypsy Nov 18 '21 at 17:17
  • Does this answer your question? [Tkinter: How to use threads to preventing main event loop from "freezing"](https://stackoverflow.com/questions/16745507/tkinter-how-to-use-threads-to-preventing-main-event-loop-from-freezing) – Thingamabobs Nov 18 '21 at 17:40
  • @MichaelGuidry, I'm not asking you to design a backend for me, just asking what is the best practice. Bryan gave me exactly what I needed. – FriendOfFriend Nov 18 '21 at 19:12

1 Answers1

0

Tkinter allows you to generate virtual events which can be bound to like any other event. This is done through the method event_generate. It is my understanding that this is safe to call from non-GUI threads.

For example, in your worker thread you can do something like this (assuming the thread has access to the root widget):

root.event_generate("<<CustomEvent>>")

Then, in the main GUI thread you can bind to this event to update the label.

root.bind("<<CustomEvent>>", do_something)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Is there a built-in mechanism for passing event parameters from the worker thread to the handler on the GUI side? – FriendOfFriend Nov 18 '21 at 19:25
  • @FriendOfFriend The underlying tk library has a way to pass strings, but unfortunately, that's not exposed at the tkinter layer. Here is one answer that shows how to work around this limitation. https://stackoverflow.com/a/23195921/7432 – Bryan Oakley Nov 18 '21 at 20:10