gpt4 book ai didi

python - 在 Tkinter 中显示 matplotlib 条形图

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:52 25 4
gpt4 key购买 nike

我正在尝试在 Tkinter 窗口中显示 matplotlib 条形图。我找到了很多关于如何放入折线图的教程,例如: http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html

但我找不到用于放入条形图的工具。我知道制作条形图的唯一方法是这样的:http://matplotlib.org/examples/api/barchart_demo.html .显然,条形图示例中导入的模块与 Tkinter 示例中的模块不同,我不确定如何让它工作,如果可以的话。

长话短说,谁能给我提供一个在 Tkinter 窗口中显示 matplotlib 条形图的示例?谢谢。

最佳答案

对于将来可能想知道的任何人,我想出了如何让它发挥作用。基本上,您的条形图必须位于 Figure 上,这样 FigureCanvasTkAgg 才能生成供 Tkinter 使用的小部件。我曾假设您需要使用 pyplot,但事实并非如此。这是我想出的:

import matplotlib, numpy, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk

root = Tk.Tk()

f = Figure(figsize=(5,4), dpi=100)
ax = f.add_subplot(111)

data = (20, 35, 30, 35, 27)

ind = numpy.arange(5) # the x locations for the groups
width = .5

rects1 = ax.bar(ind, data, width)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()

关于python - 在 Tkinter 中显示 matplotlib 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31549613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com