【问题标题】:plt.show() freezes after using plt.close('all') when calling from tkinter window从 tkinter 窗口调用时使用 plt.close('all') 后 plt.show() 冻结
【发布时间】:2021-01-19 03:00:51
【问题描述】:

代码应该等待用户点击,然后它将关闭绘图并继续。这在不从 tkinter 循环中完成时效果很好,但是如果从 tkinter 调用绘图函数,程序会冻结,直到 tkinter 窗口关闭。

因此,如果您运行此代码,您将获得一个绘图,然后当您单击该绘图时,该绘图将关闭,并且程序将显示“Hello from: main program”,这正是我想要的,但是, tkinter 窗口打开一个按钮。当您单击按钮时,绘图将再次显示,但这次当您在绘图内部单击时,绘图将关闭,但不会显示任何文本。关闭 tkinter 窗口后,文本将显示“hello from: tkinter”。

这不是我想要的,我希望像第一个示例一样单击图后立即显示文本。有人可以提供任何指导吗?

import tkinter as tk
from tkinter import *
from matplotlib import pyplot as plt

class patito():
    def __init__(self, location):
        self.x = [0,1,2,3,4,5,6]
        self.y = [1,2,1,2,1,2,1]

        self.fig, self.ax = plt.subplots()
        self.plot_this(location)
        

    def select_peak(self,event):
        plt.close("all")# close plot and continue to print("hello from:")

    def plot_this(self, location):
        plt.plot(self.x,self.y)
        self.fig.canvas.mpl_connect('button_press_event', self.select_peak)#call select_peak when clicking inside plot
        plt.show()
        print("hello from: " + location)

def call_patito(location):
    x = patito(location)

def tkinter_call_patito():
    x = patito("tkinter")
########################### Program starts Here ##############
    
call_patito("main program")
             
root = tk.Tk()
main_frame = Frame(root)
title_frame = Frame(root)

source_button =      Button(title_frame,justify=LEFT, text='Create patito object', command = tkinter_call_patito).grid(row=1, column = 1)
title_frame.pack()
main_frame.pack()
root.mainloop()

【问题讨论】:

  • 点击剧情后我得到了hello from: tkinter
  • 这很奇怪。在我的电脑上,我必须关闭 tkinter 窗口才能看到“hello from: tkinter”。你是在 Windows 上运行的吗?
  • 是 Windows 10 中的 Python 3.9.1。
  • 啊,这可要了我的命。我更新到 3.9.1 仍然是同样的问题。我得到你好:当我点击第一个情节时,主程序,但是当情节被从 tkinter 窗口调用时(在我点击按钮之后),文本“hello from: tkinter”直到我关闭后才会显示tkinter 窗口
  • 啊,看来我通过使用 matplotlib 的 Qt5Agg 后端修复了它。我尝试了 WxAgg,但对我不起作用。

标签: python matplotlib tkinter


【解决方案1】:

啊,看来我通过使用 matplotlib 的 Qt5Agg 后端修复了它。我尝试了 WxAgg,但对我不起作用。

import matplotlib
matplotlib.use('QT5Agg')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多