【问题标题】:Create a graph in a TKinter window?在 TKinter 窗口中创建图形?
【发布时间】:2025-12-26 04:05:12
【问题描述】:

我正在编写一个脚本,该脚本将运行数据并创建图表。这很容易完成。不幸的是,我使用的图形模块只能以 pdf 格式创建图形。不过,我希望将图表显示在交互式窗口中。

他们有什么方法可以将使用PyX 创建的图形添加到 TKinter 窗口中,或者将 pdf 加载到框架中或其他东西中吗?

【问题讨论】:

    标签: python tkinter pyx


    【解决方案1】:

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

    【讨论】:

      最近更新 更多