【问题标题】:Program ending early when using tkinter and pyplot使用 tkinter 和 pyplot 时程序提前结束
【发布时间】:2018-08-10 17:52:30
【问题描述】:

我正在尝试将 UI 作为输入,然后关闭它,然后使用 pyplot 进行一些绘图。但是,当我尝试使用tkinter 运行脚本并导入matplotlib.pyplot 时,程序在脚本中的root = Tk() 处终止,并且不会运行此行之后的任何命令(包括主循环)。

有没有办法在同一个脚本中同时使用tkintermatplotlib.pyplot

我正在运行的 UI 是:

from tkinter import *

class InputSelect(Frame):
    def __init__(self, master):
        self.master = master
        Frame.__init__(self, master, width=200, height=200)
        self.fillCanvas()

    def fillCanvas(self):
        self.canvas = Canvas(self, width=200, height=200)
        self.canvas.pack()

        self.aButton = Button(self, text="a", height=1, width=15, command=self.buttontest)
        self.aButtonWindow = self.canvas.create_window(100, 80, window=self.aButton)

        self.pack()

    def buttontest(self):
        print("buttontest")

def generateInputSelect():
    print("test")
    root = Tk()
    print("test2")
    app = InputSelect(root)
    app.mainloop()

if __name__ == "__main__":
    generateInputSelect()

这本身运行良好,但如果我在单独的脚本中使用它:

import ui
import matplotlib.pyplot


ui.generateInputSelect()

控制台打印“test”然后关闭,它没有到达“test2”。如果我删除 import matplotlib.pyplot,这个单独的脚本会按预期运行。

【问题讨论】:

  • 无法重现。

标签: python matplotlib tkinter


【解决方案1】:

经过一些讨论和进一步研究,通过终端运行程序导致我出现错误terminating with uncaught exception of type NSException

我可以通过使用手动设置 TkAgg 后端来修复此错误

import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt

正如 DonCristobal 在Matplotlib Crashing tkinter Application 建议的那样

此问题似乎与 MacOS 相关,这就是该错误无法被部分用户重现的原因。

【讨论】:

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