从tkinter窗口调用时,使用plt.close('all')后,plt.show()会冻结

2024-09-24 12:32:40 发布

您现在位置:Python中文网/ 问答频道 /正文

代码应该等待用户单击,然后关闭绘图并继续。如果不是从tkinter循环执行此操作,则效果非常好,但是如果从tkinter调用plot函数,则程序将冻结,直到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()

Tags: from文本self绘图helloplotmaintkinter
1条回答
网友
1楼 · 发布于 2024-09-24 12:32:40

啊,看来我用matplotlib的Qt5Agg后端修复了它。我试过WxAgg,但对我无效

import matplotlib
matplotlib.use('QT5Agg')

相关问题 更多 >