gwaedon
gwaedon

Reputation: 13

How to execute a command with a button and delete it before the command ends ? Python / Tkinter

I've got an interface where there is a 'Start' button. It runs a 'main' command where it starts a loop to run some measurements on a powermeter. I want to be able to click on an 'OK' button every time the measure is ready to be done. This button would replace the 'Start' button.

But when I try to destroy the button (buttonStart.destroy()) and then run the command main() , the command executes but doesn't delete the button until the very end. I've tried using threads from threading package, but it doesn't really work.

If there is a way to both destroy the button and run a command, I would be very interested !

Thanks a lot

Upvotes: 0

Views: 118

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

The event loop must be given the opportunity to process events in order for the window to be removed from the screen.

There are a couple of ways to make that happen. The first is to call the update_idletasks method on any widget. That is usually enough to process the event related to the destruction of the widget, though it may be necessary to call update instead. Calling update should be avoided if at all possible. My rule of thumb is to start with update_idletasks. If that doesn't work, switch to update or switch to using after.

def my_custom_function():
    startButton.destroy()
    root.upddate_idletasks()
    main()

The second method is to run your main function via after or after_idle. This will let tkinter naturally process all pending events before starting main. I would argue that this is the best approach. I recommend trying after_idle first, and if that doesn't work, switch to after with a small delay.

def my_custom_function():
    startButton.destroy()
    root.after_idle(main)

Upvotes: 2

Related Questions