Dodomac
Dodomac

Reputation: 303

How to programmatically quit mainloop via a tkinter canvas Button

My program generates several graphs one at a time and each has a quit button. The program pauses in mainloop until I press the button, then generates the next graph.

I would like a way to programmatically press or invoke the action associated to that button, in this case root.quit()

I have tried calling invoke() on the button but this doesn't work. My feeling is that the event is lost before mainloop is started.

from tkinter import * 

pause = False # passed in as an arg

root = Tk()
root.title(name)

canvas = Canvas(root, width=canvas_width, height=canvas_height, bg = 'white') 
canvas.pack()

quit = Button(root, text='Quit', command=root.quit)
quit.pack()

# make sure everything is drawn
canvas.update()        

if not pause:
    # Invoke the button event so we can draw the next graph or exit
    quit.invoke()

root.mainloop()

Upvotes: 1

Views: 1683

Answers (1)

Dodomac
Dodomac

Reputation: 303

I realised that the problem was with the event being lost and mainloop blocking so I used the pause arg to determine when to run mainloop, i.e. on the last graph.

See Tkinter understanding mainloop

All graphs are displayed and when you press Quit on any window all windows disappear and the program ends.

If there is a better way to do this please let me know, but this works.

root = Tk()
root.title(name) # name passed in as an arg

# Creation of the canvas and elements moved into another function
draw( root, ... )

if not pause:
    root.update_idletasks()
    root.update()
else:
    mainloop()

Upvotes: 1

Related Questions