matplotlib 如何使用复选按钮更改Pyplot轴的属性?

dgiusagp  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(107)

我试图根据Ttk. checkbutton中的选择在pyplot中显示不同的数据。为了简单起见,在示例中我将只尝试更改标题。

import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# create data to plot
xdata = np.linspace(0, 100, 100)
ydata = 0.1*xdata ** 2

# create window
root = tk.Tk()

# create figure
fig = plt.Figure(figsize = (10, 3), dpi = 100)
ax = fig.add_subplot()
ax.plot(xdata, ydata)
plt.show()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()

i = 0
def change_title():
    global i
    i += 1
    ax.set_title(f'Title number {i}')
    print(f'Title changed to {i}')
    
change_title()
change_title()

checkbutton = ttk.Checkbutton(root, command=change_title).pack()

root.mainloop()

因此,每次调用change_title()函数时,绘图标题中的数字都会增加。
当函数直接从代码中调用时,这是有效的。然而,选中和取消选中复选框确实会调用函数(并在控制台中产生预期的输出),但不会更改标题。执行上面的代码并选中/取消选中复选框(例如4次)将给予以下结果:

  • 绘图标题将为“标题编号2”
  • 控制台将输出“标题更改为6”

我不明白为什么会发生这种情况。为什么当我直接调用change_title()函数时,标题会改变,而当从Checkbutton调用它时,标题却不会改变?

ef1yzkbh

ef1yzkbh1#

接下来,不plt.show需要www.example.com()和first canvas.draw(),但这不是问题的一部分。
以下是修订后的代码:

import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# create data to plot
xdata = np.linspace(0, 100, 100)
ydata = 0.1*xdata ** 2

# create window
root = tk.Tk()

# create figure
fig = plt.Figure(figsize = (10, 3), dpi = 100)
ax = fig.add_subplot()
ax.plot(xdata, ydata)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

i = 0
def change_title():
    global i
    i += 1
    ax.set_title(f'Title number {i}')
    print(f'Title changed to {i}')
    canvas.draw()
    
change_title()

checkbutton = ttk.Checkbutton(root, command=change_title).pack()

root.mainloop()

相关问题