【问题标题】:Tkinter Button behaviour after matplotlib plt.show()matplotlib plt.show() 后的 Tkinter 按钮行为
【发布时间】:2022-11-28 08:35:41
【问题描述】:

我正在编写一个基于 python tkinter 的 GUI,每当我按下一个按钮时,它应该在新 Windows 中显示 Matplotlib-Plots。情节应该是非排他性的,我希望能够提出尽可能多的情节。 (原App有多个按钮,我在下面缩短了)

问题是:当我单击其中一个按钮时,绘图会正确显示。当我再次关闭情节时,使用的按钮的行为变得怪异:

  1. 在 MacOS 上,它似乎在鼠标悬停时被推入
  2. 在 Windows 中,它会在剩余的运行时间中保持推送状态

    在这两个操作系统上,它都可以很好地工作。第一次使用后只有按钮的图形很奇怪。我相信这与正在运行的 plt.show() 以某种方式阻止 GUI 框架有关,但我无法确定。

    
    class Simulator:
        
        def __init__(self) -> None:
            self.startGUI()
    
        def startGUI(self):
            self.window = tk.Tk()
            frmCol2 = tk.Frame(pady=10, padx=10)
            self.btnDraw = tk.Button(master = frmCol2, text="Draw Something", width=20)
            self.btnDraw.grid(row = 1, column = 1)
            self.btnDraw.bind("<Button-1>", self.drawSth)
            frmCol2.grid(row=1, column=2, sticky="N")
    
            self.window.mainloop()
    
        def drawSth(self, event):
            if self.btnDraw["state"] != "disabled":
                self.visualizer.plotSth(self.scenario)
    
    

    绘图本身由以下类的对象可视化器完成:

    
    class RadarVisualizer:
    
        def plotClutterVelocities(self, scenario):
            scArray = np.array(scenario)
            
            plt.figure()
    
            plt.plot(scArray[:,0], scArray[:,1])
            plt.title("Some Title")
            plt.grid()
            plt.show()
    

    我检查了 MPL 后端:它是 TkAGG。 我还试图将绘图放在不同的线程中,这让 python 哭得很厉害。似乎期望这些情节在同一个线程中开始。可能是因为我使用的后端也是基于 Tkinter 的。

【问题讨论】:

    标签: python matplotlib tkinter


    【解决方案1】:

    许多窗口没有 plt.show() 的示例。样本取自here

    import tkinter as tk
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    
    i = 0
    new_windows = []
    
    data1 = {'country': ['A', 'B', 'C', 'D', 'E'],
             'gdp_per_capita': [45000, 42000, 52000, 49000, 47000]
             }
    df1 = pd.DataFrame(data1)
    
    data2 = {'year': [1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010],
             'unemployment_rate': [9.8, 12, 8, 7.2, 6.9, 7, 6.5, 6.2, 5.5, 6.3]
             }
    df2 = pd.DataFrame(data2)
    
    data3 = {'interest_rate': [5, 5.5, 6, 5.5, 5.25, 6.5, 7, 8, 7.5, 8.5],
             'index_price': [1500, 1520, 1525, 1523, 1515, 1540, 1545, 1560, 1555, 1565]
             }
    df3 = pd.DataFrame(data3)
    
    
    def f_1(win):
        global df1
        figure1 = plt.Figure(figsize=(6, 5), dpi=100)
        ax1 = figure1.add_subplot(111)
        bar1 = FigureCanvasTkAgg(figure1, win)
        bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
        df = df1[['country', 'gdp_per_capita']].groupby('country').sum()
        df.plot(kind='bar', legend=True, ax=ax1)
        ax1.set_title('Country Vs. GDP Per Capita')
    
    
    def f_2(win):
        global df2
        figure2 = plt.Figure(figsize=(5, 4), dpi=100)
        ax2 = figure2.add_subplot(111)
        line2 = FigureCanvasTkAgg(figure2, win)
        line2.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
        df = df2[['year', 'unemployment_rate']].groupby('year').sum()
        df.plot(kind='line', legend=True, ax=ax2, color='r', marker='o', fontsize=10)
        ax2.set_title('Year Vs. Unemployment Rate')
    
    
    def f_3(win):
        global df3
        figure3 = plt.Figure(figsize=(5, 4), dpi=100)
        ax3 = figure3.add_subplot(111)
        ax3.scatter(df3['interest_rate'], df3['index_price'], color='g')
        scatter3 = FigureCanvasTkAgg(figure3, win)
        scatter3.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
        ax3.legend(['index_price'])
        ax3.set_xlabel('Interest Rate')
        ax3.set_title('Interest Rate Vs. Index Price')
    
    
    def new_window():
        global i
        new = tk.Toplevel(root)
        if i == 0:
            f_1(new)
        if i == 1:
            f_2(new)
        if i == 2:
            f_3(new)
        new_windows.append(new)
        i += 1
        if i > 2:
            i = 0
    
    
    root = tk.Tk()
    
    tk.Button(root, text='new_window', command=new_window).pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      相关资源
      最近更新 更多