我是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()
您需要更改由 ax.plot
创建的Line2D
对象的颜色。将其存储在 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()