Plouff
Plouff

Reputation: 3470

Tkinter: a simple way to avoid race conditions between an event and value update?

The issue

My issue is pretty simple, but I couldn't figure out how to cope with it easily even after some googling.

So I have a checkbutton:

self.but_val = IntVar()
self.but = Checkbutton(frame, text="text", variable=self.but_val)

This checkbutton triggers updates of some file path on the GUI:

self.but.bind('<ButtonRelease-1>', 
        lambda e: self.update_files_path(e), add='+')

In update_files_path(event), I need to get the value of the checkbutton to select the file paths to be displayed:

if self.but_val.get() == 0:
    [...]
else:
    [...]

The issue I have is that I get the value of the button before the clic. And since the processing of file paths depends on different button values, I can't just use the opposite value.

My current work around

At the moment I have a function that is triggered before the clic and that save the state of the GUI:

self.but.bind('<ButtonPress-1>', lambda e,
    self.save_design_opts_state(self.buttons_to_backup,
        self.before_clic_vars_state), add='+')

Then in update_files_path(event) I call a function that infers the GUI state after the clic:

gui_state = self.get_gui_state(event)

This function is very annoying to implement, because I need to do a lot of things: 1- Check that the clic is really made on a button (to avoid a clic that starts on a button and end elsewhere!) 2- Get the value of the of all required buttons depending of their type

Is there an easier way to deal with this?

Thank you for your help!

Upvotes: 2

Views: 398

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

Don't set your own bindings. Use the command option of the checkbutton. This option lets you specify a command to be run after the value has changed. There are other ways, but this is by far the simplest, most common way to solve your problem.

Upvotes: 1

Related Questions