【问题标题】:Program does not end when plotting in tkinter在 tkinter 中绘图时程序没有结束
【发布时间】:2020-07-07 02:00:30
【问题描述】:

我实际上是在绘制一个堆积条形图和折线图,但为了简化代码,我只显示一个简单的条形图。

from tkinter import *
import matplotlib.pyplot as plt

window = Tk()

fig, ax = plt.subplots()
name = ['a', 'b', 'c']
score = [1, 2, 3]
ax.bar(name, score)
plt.savefig('Figure1.png')

window.mainloop()

代码本身运行良好,问题是当我退出 tkinter GUI 时,程序没有完全关闭,如 powershell 所示

PS C:\Users\Desktop> python temp.py
|

如果没有绘图,它会在退出 tkinter GUI 后看起来像这样

PS C:\Users\Desktop> python temp.py
PS C:\Users\Desktop> |

我相信在 tkinter 中绘制图形后我需要一些额外的结束代码?

【问题讨论】:

  • tkintermatplotlib结合使用时,正确的方法是使用Figure而不是pyplot。见官方sample。然后您的 GUI 将正确退出,而无需额外的协议。

标签: python matplotlib tkinter


【解决方案1】:

您还需要关闭图窗。给WM_DELETE_WINDOW协议绑定一个函数,关闭函数内部的图:

...

def on_quit():
    plt.close('all')
    window.destroy()

window.protocol('WM_DELETE_WINDOW', on_quit)
window.mainloop()

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多