Home > Blockchain >  Tkinter events to update the UI according to some logic happend
Tkinter events to update the UI according to some logic happend

Time:11-19

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.

CodePudding user response:

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)
  • Related