python - 在 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()
解决方案
您需要更改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()
推荐阅读
- python - Vectorize numpy 1D array function that substracts the next element and adds the previous?
- javascript - Chrome 扩展程序 - onAlarm 事件的触发时间比预期的晚
- haskell - 删除第 n 个索引
- optimization - 在 fortran 中,从输入文件中读取名称列表是否比其他方法快得多?
- python - Python 在 iframe 中请求 html 表
- javascript - 在 Safari iOS 中检测独立模式
- amazon-s3 - 批量将数据从 RDBM 传输到 S3 的最佳方法
- php - 如果有变音符号,API 不会返回任何内容
- c# - 如何以随机速度旋转物体并有一些延迟?
- python - 同时按下按钮进行另一项工作,传感器将不断在屏幕上打印数据(x=raw.input())