【问题标题】:Using python 2 or 3, matplotlib and tkinter causes an extra empty window to open on calling plt.show()使用 python 2 或 3,matplotlib 和 tkinter 会导致在调用 plt.show() 时打开一个额外的空窗口
【发布时间】:2016-09-19 13:43:41
【问题描述】:

我正在制作一个我遇到问题的交互式数据分析工具(python 2.73.43.5)。完整的程序制作用户必须与之交互然后关闭的图形。它还要求用户通过文件选择器输入文件。

问题是每当我使用plt.show() 时,都会打开一个额外的小窗口(我不想要)以及图表。然后必须关闭小窗口才能继续程序。没什么大不了的,但是有很多图表可以交互,所以总是关闭两个窗口有点痛苦。

如果Tkinter.Tk().withraw() 未注释,则只有绘图打开,但现在程序在关闭图表时挂起,我必须终止该进程。

关于如何解决这个问题的任何想法?

提前致谢。示例代码:

import matplotlib.pyplot as plt
import numpy as np
try:
    import Tkinter
except (ImportError):
    import tkinter as Tkinter
try:
    from tkFileDialog import askopenfilename
except (ImportError):
    from tkinter.filedialog import askopenfilename

# Tkinter.Tk().withdraw()

print(askopenfilename())


x = np.arange(0,5,0.1)
y = np.sin(x)

plt.plot(x,y)
plt.show()

【问题讨论】:

    标签: python python-3.x matplotlib tkinter


    【解决方案1】:

    您可以尝试命名该图形,因为当您要求它显示图形时,它可能会混淆您所指的内容

    x = np.arange(0,5,0.1)
    y = np.sin(x)
    
    fig1 = plt.figure()
    plt.plot(x,y)
    plt.show(fig1)
    

    【讨论】:

    • 很好的建议,但它不起作用。现在我可能会寻找另一个文件选择器。
    • @BBulfin 我重新运行了您的代码,是的,您是对的,打开了一个名为“tk”的小窗口。我以为你的意思是它打开了两个绘图窗口,只绘制到第二个。
    【解决方案2】:

    经过更多研究,看起来额外的窗口是一个根窗口。这个链接解释它:

    https://bytes.com/topic/python/answers/768419-askopenfilename-tkfiledialog-problem

    from Tkinter import *
    import tkFileDialog
    root = Tk()
    root.withdraw()
    file = tkFileDialog.askopenfile(parent=root)
    file_read = file.read()  #reads file
    

    【讨论】:

    • 嘿,再次感谢您的努力。这种方法实际上是我遇到问题的方式。因此注释掉了 Tk().withraw()。当您包含此 root.withdraw() 语句时,不会弹出额外的窗口,但是当您尝试关闭绘图窗口时,整个程序就会挂起/冻结。
    【解决方案3】:

    好的,我想我在 matplotlib 源代码中摸索了一下后自己解决了这个问题。我尝试将 matplotlib 后端更改为 gtk3cairo。我猜Tk().withdraw() 也影响了 matplotlib 后端。适用于我的 linux 发行版,但仍需要在 Windows 上进行测试。如果我找到适用于两者的解决方案,我将更新答案。

    编辑: matplotlib.use("Qt4agg") 在我的 Windows 版本上工作。我也通过安装 pyside 让它在 linux 上工作。不幸的是,不能与最新版本的python3一起使用

    工作代码:

    import matplotlib
    matplotlib.use("gtk3cairo")
    import matplotlib.pyplot as plt
    import numpy as np
    try:
        import Tkinter
    except (ImportError):
        import tkinter as Tkinter
    try:
        from tkFileDialog import askopenfilename
    except (ImportError):
        from tkinter.filedialog import askopenfilename
    
    Tkinter.Tk().withdraw()
    
    print(askopenfilename())
    
    
    x = np.arange(0,5,0.1)
    y = np.sin(x)
    
    fig1 = plt.figure()
    plt.plot(x,y)
    plt.show(fig1)
    

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2018-05-11
      相关资源
      最近更新 更多