简体   繁体   English

用图实现 python ttk.notebook

[英]Implement python ttk.notebook with graph

I have a tkinter GUI python ver 2.7.我有一个 tkinter GUI python ver 2.7。 The code is:代码是:

Main = Tk()
Main.tk_setPalette(background='white')
Time(Main)
init()
GenerateMenus(Main)
w = GenerateDisplay(Main)
n = ttk.Notebook(Main, width= 800, height =400)
n.grid(row=6,column=0, columnspan=9)
f1 = ttk.Frame(n);
f2 = ttk.Frame(n);
n.add(f2, text='Two')
n.add(f1, text='One')
GenerateGraph(f1)

Code for Generating Graph生成图的代码

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import *
from random import *
import Tkinter as tk

f = Figure(figsize=(5.5,3.5), dpi=120)
rc("font", size = 7)
Figure
a = f.add_subplot(111)
xList = []
yList = []
x= 0
y = 0

def animate(i):
    global x
    global y
    xList.append(int(x))
    yList.append(int(y))

    y = randint(0,100)
    x += 5

    a.clear()
    a.plot(xList, yList)
    a.set_ylim(0,100)
    a.set_xlabel("Time (s)")
    a.set_ylabel("Acceleration (m/s2)")


def GenerateGraph(Master):
    dataPlot = FigureCanvasTkAgg(f, master=Master)
    dataPlot.show()
    dataPlot.get_tk_widget().grid(row=0, column=0)

    toolbar = NavigationToolbar2TkAgg(dataPlot, Master)
    toolbar.update()
    dataPlot._tkcanvas.grid(row=1, column=0)

The rest of the GUI is displayed but the graph is not.显示 GUI 的其余部分,但不显示图形。 I am new to tkinter and would like to know how to edit this code so that the graph shows inside a notebook tab.我是 tkinter 的新手,想知道如何编辑此代码,以便图表显示在笔记本选项卡中。

All you have to do is pass the notebook variable ie n as the Master in the line 您所要做的就是传递笔记本变量,即n作为行中的Master

dataPlot = FigureCanvasTkAgg(f, master=Master)

and hence you would not need the lines 因此,您不需要线

dataPlot.show()
dataPlot.get_tk_widget().grid(row=0, column=0)

Mr Parate,帕拉特先生,

I couldn't find this information in any place but here and it worked to me in python 3.8.我在任何地方都找不到此信息,但在这里,它在 python 3.8 中对我有用。 It opened the plot in n not in one of the tabs though.它在 n 中而不是在其中一个选项卡中打开了绘图。 I had to do (in my OOP version):我必须这样做(在我的 OOP 版本中):

self.f1 = ttk.Frame(n); self.f1 = ttk.Frame(n); self.f2 = ttk.Frame(n); self.f2 = ttk.Frame(n);

#and then #接着

    self.canvas = FigureCanvasTkAgg(fig, master=self.ica_Tab_01) 
    self.canvas.draw()

    # position of canvas:
    self.canvas.get_tk_widget().grid(row=1, rowspan=2, column=0, columnspan=20, sticky='NEWS')

and it worked fine.它工作得很好。 Thank you very much!非常感谢你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM