【问题标题】:How to change the plot color after a button press in matplotlib/tkinter?在 matplotlib/tkinter 中按下按钮后如何更改绘图颜色?
【发布时间】:2019-04-24 13:48:56
【问题描述】:

我是 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()

【问题讨论】:

    标签: python matplotlib plot tkinter interactive


    【解决方案1】:

    您需要更改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()
    

    【讨论】:

    • 谢谢!这就是我一直在寻找的。这和我改变颜色以外的其他东西的方式一样吗?比如数据?
    • 是的,例如你可以使用line.set_ydata
    猜你喜欢
    • 2013-07-16
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2021-07-31
    • 2014-02-22
    • 2019-10-13
    相关资源
    最近更新 更多