如何在 matplotlib/tkinter 中按下按钮后更改绘图颜色?
How to change the plot color after a button press in matplotlib/tkinter?
我是 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()
我是 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()