【问题标题】:Tkinter : Plot (Graph) results in popup windowTkinter:在弹出窗口中绘制(图形)结果
【发布时间】:2019-09-05 05:20:35
【问题描述】:

这是帮助我在 python 上绘图的线。

packing_options[best_index].plot_sheets()

这就是它在 python 上的样子。这是图表的图片。 https://imgur.com/a/fRczosW

现在,我正在尝试 tkinter。我希望图表弹出。我怎样才能做到这一点 ?

window = tk.Tk()
packing_options[best_index].plot_sheets()
window.mainloop()

我试过这个。但是没用。

编辑: 因此,“matplotlib 将按照某人的评论使用。 这是代码:

def plot_sheet(self):
    fig,ax = plt.subplots(1)
    ax.set_xlim([0, self.W]) 
    ax.set_ylim([0, self.L]) 
    recs = []
    for i in range(len(self.rect_list)):
        if self.rect_rotate[i]:
            ax.add_patch(patches.Rectangle((self.rect_pos[i][0], self.rect_pos[i][1]), self.rect_list[i].l, self.rect_list[i].w,linewidth=3,edgecolor='r'))
        else:
            ax.add_patch(patches.Rectangle((self.rect_pos[i][0], self.rect_pos[i][1]), self.rect_list[i].w, self.rect_list[i].l,linewidth=3,edgecolor='r'))
    plt.show()

def plot_sheets(self):
    for i in range(len(self.sheets)):
        self.sheets[i].plot_sheet()

这是绘图的代码。 pack_options[best_index] 也是这里的一个函数。它绘制了大约 10-20 个图,因为有一个循环。 如何在这里应用 matplotlib 后端?

【问题讨论】:

  • 您想在新窗口中显示您的图像吗?如果是这样,请查看TopLevel widget
  • 不是图片,而是图表。
  • 对于图形,您需要使用 matplotlib 后端进行 tkinter。可以在here 找到一个示例。将您的画布放在 TopLevel 窗口上并在那里绘制图表。
  • 这个弹出窗口还有其他方法吗?
  • 不,在 tkinter 中没有其他方法可以弹出窗口。实现上述方法非常简单。

标签: python python-3.x tkinter tkinter-canvas


【解决方案1】:

我无法运行它,但它可能是这样的

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import matplotlib.pyplot as plt

import tkinter as tk

class YourClass():

    def plot_sheet(self):
        fig,ax = plt.subplots(1)
        ax.set_xlim([0, self.W]) 
        ax.set_ylim([0, self.L]) 
        recs = []
        for i in range(len(self.rect_list)):
            if self.rect_rotate[i]:
                ax.add_patch(patches.Rectangle((self.rect_pos[i][0], self.rect_pos[i][1]), self.rect_list[i].l, self.rect_list[i].w,linewidth=3,edgecolor='r'))
            else:
                ax.add_patch(patches.Rectangle((self.rect_pos[i][0], self.rect_pos[i][1]), self.rect_list[i].w, self.rect_list[i].l,linewidth=3,edgecolor='r'))
        #plt.show()
        return fig

#--- main ---

window = tk.Tk()

packing_options = [YourClass(), YourClass(), YourClass()]
best_index = 0

fig = packing_options[best_index].plot_sheets()

dataPlot = FigureCanvasTkAgg(fig, master=master)
dataPlot.show()
dataPlot.get_tk_widget().pack(side='top', fill='both', expand=1) 

window.mainloop()

【讨论】:

  • 这很有帮助。但我的案例有 15-20 个图表。所以,当我触发这个命令时,所有的图都立刻出现了。有没有办法用下一个按钮或其他东西来显示?
  • 您必须将绘图创建为分隔figures,然后您可以显示一个图形,您可以添加两个tk.Button 以显示下一个/上一个figure
  • 有参考吗?我很难找到它。
  • 在我的examples on GitHub 中我在文档Embedding In Tk¶ 中找到了示例链接
  • 我收到此错误:NameError: name 'master' is not defined。将其更改为自我/画布。还是一样。
猜你喜欢
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 2012-08-28
  • 2020-09-05
  • 2016-02-08
相关资源
最近更新 更多