在TKinter窗口中创建图表?

2 投票
1 回答
4688 浏览
提问于 2025-04-17 05:19

我正在写一个脚本,这个脚本会处理一些数据并生成图表。这部分很简单,已经完成了。不过,我现在用的图表模块只能把图表保存为PDF格式。我希望能在一个互动窗口中显示这些图表。

有没有办法把用PyX生成的图表放到TKinter窗口里,或者把PDF加载到一个框架里呢?

1 个回答

3

你需要把PyX生成的输出转换成位图,这样才能把它放到你的Tkinter应用程序里。虽然没有简单的方法可以直接把PyX的输出变成PIL图像,但你可以使用pipeGS这个方法来准备位图,然后用PIL来加载它。下面是一个非常简单的例子:

import tempfile, os

from pyx import *
import Tkinter
import Image, ImageTk

# first we create some pyx graphics
c = canvas.canvas()
c.text(0, 0, "Hello, world!")
c.stroke(path.line(0, 0, 2, 0))

# now we use pipeGS (ghostscript) to create a bitmap graphics
fd, fname = tempfile.mkstemp()
f = os.fdopen(fd, "wb")
f.close()
c.pipeGS(fname, device="pngalpha", resolution=100)
# and load with PIL
i = Image.open(fname)
i.load()
# now we can already remove the temporary file
os.unlink(fname)

# finally we can use this image in Tkinter
root = Tkinter.Tk()
root.geometry('%dx%d' % (i.size[0],i.size[1]))
tkpi = ImageTk.PhotoImage(i)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=i.size[0],height=i.size[1])
root.mainloop()

撰写回答