我是Python的新手。我想在按下按钮后更新显示的图表。例如,我想改变颜色。
谢谢你的帮助!
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class App(Frame):
def change_to_blue(self):
# todo self.ax.plot.color = 'blue' ????
# todo self.fig.update() ???
print('graph should be blue now instead of red')
def __init__(self, master):
Frame.__init__(self, master)
Button(master, text="Switch Color to blue", command=lambda: self.change_to_blue()).pack()
self.fig = Figure(figsize=(6, 6))
self.ax = self.fig.add_subplot(111)
self.ax.plot(x, y, color='red')
self.canvas = FigureCanvasTkAgg(self.fig, master=master)
self.canvas.draw()
self.canvas.get_tk_widget().pack()
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
root = Tk()
app = App(root)
root.mainloop()
您需要更改Line2D
创建的ax.plot
对象的颜色。将它存储在self
中,然后您就可以在动作处理程序中访问它。
def __init__(self, master):
...
# ax.plot returns a list of lines, but here there's only one, so take the first
self.line = self.ax.plot(x, y, color='red')[0]
然后,您可以在处理程序中更改所述行的颜色。您需要调用canvas.draw
来强制重新呈现该行。
def change_to_blue(self):
self.line.set_color('blue')
self.canvas.draw()