如何通过 tkinter canvas 按钮以编程方式退出 mainloop
How to programmatically quit mainloop via a tkinter canvas Button
我的程序一次生成多个图表,每个图表都有一个退出按钮。
程序暂停 mainloop
直到我按下按钮,然后生成下一个图形。
我想要一种以编程方式按下或调用与该按钮关联的操作的方法,在本例中为 root.quit()
我试过在按钮上调用 invoke()
,但这不起作用。我的感觉是事件在 mainloop
开始之前就丢失了。
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()
我意识到问题在于事件丢失和 mainloop
阻塞,所以我使用 pause
arg 来确定何时 运行 mainloop
,即最后一张图。
见
显示所有图表,当您在任何 window 上按退出时,所有 windows 消失,程序结束。
如果有更好的方法,请告诉我,但这是可行的。
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()
我的程序一次生成多个图表,每个图表都有一个退出按钮。
程序暂停 mainloop
直到我按下按钮,然后生成下一个图形。
我想要一种以编程方式按下或调用与该按钮关联的操作的方法,在本例中为 root.quit()
我试过在按钮上调用 invoke()
,但这不起作用。我的感觉是事件在 mainloop
开始之前就丢失了。
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()
我意识到问题在于事件丢失和 mainloop
阻塞,所以我使用 pause
arg 来确定何时 运行 mainloop
,即最后一张图。
见
显示所有图表,当您在任何 window 上按退出时,所有 windows 消失,程序结束。
如果有更好的方法,请告诉我,但这是可行的。
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()