【问题标题】:The python program is not ending when tkinter window is closed关闭tkinter窗口时python程序没有结束
【发布时间】:2019-08-07 15:08:43
【问题描述】:

我正在做一个项目来制作像 GUI 一样的示波器。虽然 GUI 还没有准备好,但是当我关闭 TKinter 窗口时,我遇到了一个问题,即程序没有被关闭。它仍在 python shell 中运行。我认为这可能是关闭 tkinter 相关程序的方法。但我发现程序只需关闭 tkinter 窗口就可以杀死程序。在我的情况下,即使关闭 tkinter 窗口,程序也在 python shell 中运行。我把我的代码放在这里,看看问题出在哪里?

from tkinter import *
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

root = Tk()
root.geometry("800x500+100+100")
root.title('root window')

frame = Frame(root, borderwidth=1,bg="#0DBDAB") ## This is the frame in which plot will be shown
frame.place(relx=1.0/3,rely=0.5, anchor="center", relwidth=0.60,relheight=0.8)
xar = [0]
yar = [0]
k=0.2  ### This is just a constant to make plot smoother
style.use('ggplot')
fig = plt.figure(figsize=(20,20), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)
ax1.set_ylim(-1, 1)
line, = ax1.plot(xar, yar, 'r')

## It will not plot regularly instead add line for new data
def animate(i):
    ax1.set_xlim(left=max(0,i-20), right=i+1)
    yar.append(np.sin(i*k))
    xar.append(i)
    line.set_data(xar,yar)
    return line,

plotcanvas = FigureCanvasTkAgg(fig, frame)
plotcanvas.get_tk_widget().pack(side=BOTTOM,fill=BOTH,expand=True)
ani = animation.FuncAnimation(fig, animate, interval=1000, blit=False)

root.mainloop()

【问题讨论】:

    标签: python matplotlib animation tkinter matplotlib-widget


    【解决方案1】:

    我做了一个小改动,无论如何你必须使用这个

    root.protocol("WM_DELETE_WINDOW", quit_me)

    见下文,在我的 debian 上,从终端启动脚本并关闭它工作的 tkinter 窗口。

    from tkinter import *
    from matplotlib import pyplot as plt
    import matplotlib.animation as animation
    from matplotlib import style
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import numpy as np
    
    def quit_me():
        print('quit')
        root.quit()
        root.destroy()
    
    root = Tk() 
    root.protocol("WM_DELETE_WINDOW", quit_me)
    root.geometry("800x500+100+100")
    root.title('root window')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2018-02-01
      • 2020-07-29
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多