【发布时间】:2023-03-25 06:47:03
【问题描述】:
我正在编写一个程序来处理一些数据并将结果显示为图表。我将绘图附加到画布上,以便它可以显示在同一个 Tkinter 窗口中,而不是显示在新窗口中。我希望当用户使用mpl_connect 单击它时,该图将显示在单独的窗口中。但是,它只工作一次。如果我第二次单击画布,则没有任何反应。我也尝试过制作一个按钮并将一个事件绑定到它,但同样的问题发生了:它只工作一次。
谁能告诉我我犯了什么错误以及如何解决它?
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from Tkinter import *
class mclass:
def __init__(self, window):
self.window = window
self.leftframe= Frame (self.window)
self.rightframe= Frame (self.window)
self.leftframe.pack (side= LEFT, anchor=N)
self.rightframe.pack (side=RIGHT, anchor=N)
self.box = Entry(self.leftframe)
self.button = Button (self.leftframe, text="check", command=self.plot)
self.plotlabel= Label (self.leftframe, text="The following is the plot")
self.box.grid (row=1, column=1)
self.button.grid(row=2, column= 1)
self.plotlabel.grid (row=3, column=1)
def plot (self):
x=np.array ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
v= np.array ([16,16.31925,17.6394,16.003,17.2861,17.3131,19.1259,18.9694,22.0003,22.81226])
p= np.array ([16.23697, 17.31653, 17.22094, 17.68631, 17.73641 , 18.6368,
19.32125, 19.31756 , 21.20247 , 22.41444 , 22.11718 , 22.12453])
fig = plt.figure(figsize=(6,6))
a = fig.add_subplot(111)
a.scatter(v,x,color='red')
a.plot(p, range(2 +max(x)),color='blue')
a.invert_yaxis()
a.set_title ("Estimation Grid", fontsize=16)
a.set_ylabel("Y", fontsize=14)
a.set_xlabel("X", fontsize=14)
canvas = FigureCanvasTkAgg(fig, master=self.rightframe)
canvas.get_tk_widget().grid(row=1, column= 2)
canvas.draw()
cid= fig.canvas.mpl_connect('button_press_event', lambda event: plt.show())
window= Tk()
start= mclass (window)
window.mainloop()
【问题讨论】:
-
怀疑您遇到了
pyplot固有的全局状态问题。我会不惜一切代价避免使用pyplot+ 嵌入。
标签: python numpy matplotlib tkinter event-handling