Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 获取两个单独的tkinter窗口,而不是浏览3页_Python 3.x_Csv_Matplotlib_Tkinter_Tkinter Canvas - Fatal编程技术网

Python 3.x 获取两个单独的tkinter窗口,而不是浏览3页

Python 3.x 获取两个单独的tkinter窗口,而不是浏览3页,python-3.x,csv,matplotlib,tkinter,tkinter-canvas,Python 3.x,Csv,Matplotlib,Tkinter,Tkinter Canvas,我正在尝试将matplot中的图形组合到tkinter窗口中,并能够在不同的图形中导航。我已经试过做实验了,上面有一张图表。但是,我从tkinter获得了2个窗口,而不是1个 我已经插入了到目前为止我所做的代码: import tkinter as tk from tkinter import ttk import matplotlib matplotlib.use('TkAgg') import numpy as np from matplotlib.backends.backend_tka

我正在尝试将matplot中的图形组合到tkinter窗口中,并能够在不同的图形中导航。我已经试过做实验了,上面有一张图表。但是,我从tkinter获得了2个窗口,而不是1个

我已经插入了到目前为止我所做的代码:

import tkinter as tk
from tkinter import ttk
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, 
NavigationToolbar2Tk
from tkinter import *
import tkinter.messagebox as tm


LARGE_FONT=("Verdana", 12) #font type and font size

df1= pd.read_csv(r"U:\\GE90\nodes_fixed.csv")

df2 = pd.read_csv(r"U:\\GE90\edge_list_3_fixed.csv")

g=nx.Graph()
# Add edges and edge attributes
for i, elrow in df2.iterrows():
# g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict())  # 
deprecated after NX 1.11
g.add_edge(elrow[0], elrow[1], **elrow[2:].to_dict())

app=Tk()

class Trial(tk.Tk):

#self -implied but does not need to be passed at all depending on the 
structure
#* = args   --> arguments, unlimited number of variables --> can pass 
through as many variables as you want
#** = kwargs --> keyboard arguments, passing through dictionaries 
def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)
    tk.Tk.wm_title(self, "Trial Only")
    container = tk.Frame(self)

    container.pack(side="top", fill="both", expand = True)

    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)

    self.frames = {}

    for F in (StartPage, PageOne, PageTwo, plot):

        frame = F(container, self)

        self.frames[F] = frame

        frame.grid(row=0, column=0, sticky="nsew")

    self.show_frame(StartPage)

def show_frame(self, cont):

    frame = self.frames[cont]
    frame.tkraise()



class StartPage(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self,parent)
    label = tk.Label(self, text="Start Page", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button = ttk.Button(self, text="Visit Page 1",
                       command=lambda: controller.show_frame(PageOne))
    button.pack()

#Adding a page

class PageOne(tk.Frame):
def __init__(self, parent, controller):

    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Page One", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button1 = ttk.Button(self, text="Back to home",
                           command=lambda: 
controller.show_frame(StartPage))
    button1.pack()

    button2 = ttk.Button(self, text="Visit page two",
                        command=lambda: controller.show_frame(PageTwo))
    button2.pack()

class PageTwo(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
    label.pack(pady=10,padx=10)

    button3 = ttk.Button(self, text="Back to Home",
                        command=lambda: controller.show_frame(StartPage))
    button3.pack()

    button4 = ttk.Button(self, text="Page One",
                        command=lambda: controller.show_frame(PageOne))
    button4.pack()

    button5 = ttk.Button(self, text="Visit Page 3",
                        command=lambda: controller.show_frame(PageThree))
    button5.pack()

class plot (tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label= tl.Label(self, text= "Figure 1", font = LARGE_FONT)
        label.pack(pady=10,padx=10)


# Edge list example
        print(elrow[0]) # node1
        print(elrow[1]) # node2
        print(elrow[2:].to_dict()) # edge attribute dict


# Add node attributes
for i, nlrow in df1.iterrows():
# g.node[nlrow['id']] = nlrow[1:].to_dict()  # deprecated after NX 1.11
nx.set_node_attributes(g, {nlrow['ID']:  nlrow[1:].to_dict()}) 

# Node list example
print(nlrow)

# Preview first 5 edges

list(g.edges(data=True))[0:5] 

# Preview first 10 nodes

list(g.nodes(data=True))[0:10] 

print('# of edges: {}'.format(g.number_of_edges()))
print('# of nodes: {}'.format(g.number_of_nodes()))

# Define node positions data structure (dict) for plotting
for node in g.nodes(data=True):
print(node)
print("")
node_positions = {node[0]: (node[1]['X'], -node[1]['Y']) for node in 
g.nodes(data=True)}

# Preview of node_positions
dict(list(node_positions.items())[0:5])

# Define data structure (list) of edge colors for plotting

# edge_colors = [e[2]['color'] for e in g.edges(data=True)]  
edge_colors = [e[2]['color'] for e in list(g.edges(data=True))]

# Preview first 10
edge_colors[0:10]
fig = plt.figure(figsize=(8, 6))
nx.draw(g, pos=node_positions, edge_color=edge_colors, node_size=10, 
node_color='black')
plt.title('Graph Representation of repair trail', size=15)




canvas = FigureCanvasTkAgg(fig, app)
canvas.get_tk_widget().pack()
canvas.draw()


app = Trial()
app.mainloop()
我想从tkinter显示一个窗口来显示所有不同的页面,但是,输出给我tkinter的两个不同窗口 第一个是所有起始页和按钮
第二,仅使用类plot中的图形,就可以显式地创建两个窗口

第一行是:
app=Tk()


第二行是
app=Trial()
,因为
Trial
继承自
tk.tk

您将获得两个窗口,因为您使用
app=Tk()
创建了第一个窗口,然后在初始化
Trial
时创建了第二个窗口,因为它继承自
Tk
。事实上,您不需要
app=Tk()

您希望绘图位于其中一个页面中,因此需要将创建matplotlib图形的所有代码移动到
页面
类中,例如
第二页

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two")
        label.pack(pady=10, padx=10)

        # code for the plot
        fig = plt.figure(figsize=(8, 6))  # create matplotlib figure
        # add axes and plot (replace this by your matplotlib code)
        ax = fig.subplots() 
        ax.plot(range(10))
        ax.set_title('Graph Representation of repair trail', size=15)
        # create the tkinter widget to display the figure
        canvas = FigureCanvasTkAgg(fig, self)  # here self is the widget in which you want to display the figure
        canvas.get_tk_widget().pack()
        toolbar = NavigationToolbar2Tk(canvas, self)  # add toolbar
        canvas.draw()  # show content

        # navigation button 
        button3 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button3.pack()

        button4 = ttk.Button(self, text="Page One",
                            command=lambda: controller.show_frame(PageOne))
        button4.pack()

您使用
app=Tk()
创建第一个窗口,然后在初始化
Trial
时创建第二个窗口,因为它继承自
Tk
。我认为您可以删除行
app=Tk()
,因为您稍后会用
app=Trial()
覆盖它。顺便说一句,您的代码中存在缩进问题,您发布的代码超出了a的需要。@j_4321我为代码混乱和发布的代码太多而道歉。我是新的编码和堆栈溢出。我想进一步询问关于用app=Trial()替换app=Tk()的问题。我刚刚在我的代码上尝试了它,它给了我一个错误名称错误:名称“app”没有定义,请修复问题中的缩进。由于出现错误,这意味着您正在使用
app
之前的
app=Trial()
。要么你想把
Trial
作为根窗口,在本例中,在
canvas=FigureCanvasTkAgg(fig,app)
之前创建它,要么你不想,在本例中,让
Trial
Frame
继承并将其打包到app中。@j_4321我已经这样做了,但它确实将两者结合了起来,我无法离开绘图,尽管点击了不同的页面,但它仍会显示您需要在其中一个页面中创建绘图:首先创建
试用版
,然后使用
canvas=FigureCanvasTkAgg(图,)
创建图形,例如,用PageOne替换master(存储在
app.frames
)。似乎您正在尝试将您不理解的代码组合在一起,因此我建议您花时间分别分析每段代码,并首先使用tkinter查看OOP的简单示例。如果我将app=Trial()移到画布行上方,它确实将它们结合在一起,但我无法改变页面远离图形。我可以问“canvas.get__widget().pack()”是什么吗?什么是.get_tk_widget?@ElizabethDC
canvas.get_tk_widget()
返回包含matplotlib图的tkinter小部件。
pack
是用于在页面中显示此小部件的方法,您也可以使用
grid
place
。我已将代码替换为:
fig=figure()canvas=plt.figure(figsize=(8,6))nx.draw(g,pos=node\u positions,edge\u color=edge\u colors,node\u size=10,node\u color='black')plt.title('repair trail的图形表示法',size=15)toolbar=NavigationToolbar2Tk(canvas,self)canvas.draw()
如果我错了,请纠正我,但fig=fig()提供空白画布?我已经试过了,但是:
AttributeError:'NoneType'对象没有属性“bbox”
我不确定bbox来自哪里?根据你发布的代码,你应该有
fig=plt.figure(figsize=(8,6))
canvas=FigureCanvasTkAgg(fig,self)
。不是
canvas=plt.figure(figsize=(8,6))
,因为
canvas
是包含图形的
figurecavastkagg
,而不是matplotlib图形。这对我来说是有意义的。但是,我不明白为什么我现在会出现一个错误,
NameError:name'fig'没有定义
?我们将fig定义为
fig=plt.figure(figsize=(8,6))
?那么为什么这个返回图没有定义呢?我刚刚将所有其他计算代码移到代码顶部,这会影响它吗?