简体   繁体   English

AttributeError:object 没有属性 matplot tk 和类 python

[英]AttributeError: object has no attribute matplot tk and classes python

I am reciving the error: AttributeError: 'DES' object has no attribute 'summary_output' So pretty much im calling this Set class set_summary method using this function inside the upload_csv file, which is called upload我收到错误: AttributeError: 'DES' object has no attribute 'summary_output' 所以几乎我在 upload_csv 文件中使用这个 function 调用这个 Set class set_summary 方法,这被称为上传

upload_csv_class上传_csv_类

def upload():
    global summary
    xvalues = []
    yvalues = []
    xyvalues = []
    header = []
    
    summary.clear()
    xvalues.clear()
    yvalues.clear()
    xyvalues.clear()
    header.clear()
    
    filename = filedialog.askopenfilename()
    if len(filename) != 0:
        print('Selected:', filename)
        with open(filename) as file:
            csvreader = csv.reader(file)
            header.append(next(csvreader)) 
            for row in csvreader:
                if len(row) == 3:
                    xvalues.append(int(row[0]))
                    yvalues.append(int(row[1]))
                    xyvalues.append(int(row[2])) 
                elif len(row) == 2:
                    xvalues.append(row[0])
                    yvalues.append(row[1])  
        if len(header[0]) == 3:                    
            summary.append(header[0])
            summary.append(yvalues)
            summary.append(yvalues)
            summary.append(xyvalues)  
            
        if len(header[0]) == 2:                    
            summary.append(header[0])
            summary.append(xvalues)
            summary.append(yvalues)  
            summary.append([])               
        
        s = Set(summary)   
        s.set_summary()  

This has no issues and correctly passes the variable data through the set class, to the set_summary function inside my Set file.这没有问题,并通过集合 class 正确地将变量数据传递到我的 Set 文件中的 set_summary function。

This is where it gets a bit tricky.这是它变得有点棘手的地方。

So I get this error when parsing the summary value from my set class to my test file/DES Class.因此,在将汇总值从我的集合 class 解析到我的测试文件/DES Class 时出现此错误。

This is my Set Class这是我的套装 Class

class Set:
    def __init__ (self, summary):
        self.summary = summary
        
    def set_summary(self):
        print(self.summary)
        s = DES(self.summary)   
        s.set_summary_text()

I am wanting to add the summary value to my DES class object, so that I can have multiple tkinter frames/windows.我想将摘要值添加到我的 DES class object,这样我就可以拥有多个 tkinter 帧/窗口。

The error I get is exactly:我得到的错误是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\tbyrm\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\***\Documents\Workspace\***\***\view\upload_csv.py", line 120, in upload
    s.set_summary()
  File "C:\Users\***\Documents\Workspace\***\***\view\Set.py", line 23, in set_summary
    s.set_summary_text()
  File "C:\Users\***\Documents\Workspace\***\***\view\test.py", line 174, in set_summary_text
    self.summary_output.configure(state='normal')
AttributeError: 'DES' object has no attribute 'summary_output'

Here is my DES Class:这是我的 DES Class:

class DES(Frame):
    def __init__(self, summary):
        self.summary = summary
        
    def createFrame(self, master):
        global i
        self.frame = tk.Frame(master, width=750, height=968,bg='white')
        self.upload_button = tk.Button(
                self.frame, 
                text="Add Data",
                fg="DodgerBlue4",
                font=("Graph Type", 15),
                height=1, width=12,
                borderwidth=2,
                relief="groove",
                command=upload)

        self.des_button = tk.Button(
                        self.frame,
                        text="New DES",
                        fg="DodgerBlue4",
                        font=("Graph Type", 15),
                        height=1, width=12,
                        borderwidth=2,
                        relief="groove",
                        command=self.new_des)
        
        self.comb_csv_button = tk.Button(
                        self.frame,
                        text="Combine CSV",
                        fg="DodgerBlue4",
                        font=("Graph Type", 15),
                        height=1, width=12,
                        borderwidth=2,
                        relief="groove",
                        command=self.new_des)        

        self.logout_buttotn = tk.Button(
                        self.frame,
                        text="Logout",
                        font=("Arial", 15),
                        height=1, width=12,
                        borderwidth=2,
                        relief="groove",
                        fg="red",
                        command = self.close)

        self.chat_submit_button = tk.Button(
                            self.frame,
                            text="Submit",
                            font=("Arial", 9),
                            height=1, width=12,
                            command=self.set_chat_text,
                            borderwidth=2,
                            relief="groove")

        self.chat_input = tk.Entry(
                        self.frame, 
                        width=55,
                        font=("Arial", 14), highlightthickness=0,
                        bg="white", borderwidth=1, relief="solid")

        self.summary_output = tk.Text(
                        self.frame, 
                        height=8,
                        width=78,
                        bg="gray95",
                        borderwidth=2, 
                        relief="groove",
                        font=("Arial", 12))

        self.summary_output.configure(state='disabled') 

        self.chat_output = tk.Text(
                        self.frame, 
                        height=8,
                        width=78,
                        bg="gray95",
                        borderwidth=2, 
                        relief="groove",
                        font=("Arial", 12))

        self.chat_output.insert(INSERT, "Chat: \n")
        self.chat_output.configure(state='disabled')  

        n = tk.StringVar()

        self.combo_box_graph = ttk.Combobox(
                                self.frame,
                                width=14,
                                justify='center',
                                textvariable=n,
                                font=("Arial", 22),
                                state="readonly")

        self.combo_box_graph['values'] = (
                                'Select',
                                'Line Graph',
                                'Bar Graph',
                                'Histogram',
                                'Scatter Graph')

        self.combo_box_graph.current(0)
        self.combo_box_graph.bind("<<ComboboxSelected>>", self.view_graph)

        font = Font(family = "Helvetica", size = 12)
        self.frame.option_add("*TCombobox*Listbox*Font", font)
        
                # IMPLEMENTING GRAPH ------------------------------------------------------

        fig = Figure(figsize=(5, 4), dpi=130) # Create graph figure
        self.plt = fig.add_subplot(111) # Add plots
        self.canvas = FigureCanvasTkAgg(fig, master)  # tk implementation
        self.canvas.draw() # Create the graph canvas

        # # IMPLEMENTING TOOLBAR ----------------------------------------------------

        toolbarFrame = Frame(master) 
        toolbarFrame.pack(side=TOP, fill=BOTH) # Place toolbar at top of screen
        toolbar = NavigationToolbar2Tk(self.canvas, toolbarFrame)
        
        
        self.upload_button.place(x=20, y=560)
        self.combo_box_graph.place(x=170, y=560)
        self.comb_csv_button.place(x=0, y=600)
        self.summary_output.place(x=20, y=610)
        self.chat_output.place(x=20, y=770)
        self.chat_input.place(x=20, y=920)
        self.chat_submit_button.place(x=633, y=920)
        self.logout_buttotn.place(x=585, y=560)
        self.canvas.get_tk_widget().place(x=50, y=30)
        if i == 0:
            self.des_button.place(x=395, y=560)
        i += 1
        
        self.frame.pack()
        

    def new_des(self):
        self.newWindow = tk.Toplevel(root)
        s = DES("")                        
        s.createFrame(self.newWindow)
        
    def close(self):
        root.destroy()    
    
    def set_chat_text(self):
        self.chat_output.configure(state='normal')
        self.chat_output.insert('end', self.chat_input.get() + '\n')
        self.chat_output.configure(state='disabled') 
        self.chat_input.delete(0, END) 

    def set_summary_text(self):
        self.summary_output.configure(state='normal')
        self.summary_output.delete('1.0', END) # Remote all text
        if len(summary[0]) == 3:
            text =  summary[0][0]+ ": " + str(summary[1]).replace('[','').replace(']','') + "\n\n" + summary[0][1] + ": " + str(summary[2]).replace('[','').replace(']','') + "\n\n" + summary[0][2] + ": " + str(summary[3]).replace('[','').replace(']','')
        if len(summary[0]) == 2:
            text =  summary[0][0]+ ": " + str(summary[1]).replace('[','').replace(']','') + "\n\n" + summary[0][1] + ": " + str(summary[2]).replace('[','').replace(']','')
        self.summary_output.insert('end',text)
        self.summary_output.configure(state='disabled')  #Make text widget read only 
        
        
    def view_graph(self, event):
        print("test")
        self.plt.cla()    
        if len(self.summary) != 0:
            self.header = self.summary[0]
            x = self.summary[1]
            y = self.summary[2]
            self.x_y_range = self.summary[3]
            self.xlabel = self.header[0]
            self.ylabel = self.header[1]
            self.plt.set_xlabel(self.xlabel)
            self.plt.set_ylabel(self.ylabel)
                
            if len(self.header[0]) >= 3:
                self.xylabel = self.header[2]
                
            if self.combo_box_graph.get() == "Line Graph":
                self.plt.plot(x, y)     
                self.plt.set_title("Line Graph") 
                self.canvas.draw()
                
            if self.combo_box_graph.get() == "Bar Graph":
                self.ind = numpy.arange(len(x))
                self.width = .8
                self.plt.ax.bar(self.ind, y, self.width)
                self.plt.ax.set_title("Bar Graph")
                self.canvas.draw()
                
            if self.combo_box_graph.get() == "Histogram":
                self.plt.ax.hist(y, density=True, bins=82, label=self.ylabel)
                self.mn, self.mx = self.plt.ax.set_xlim()
                self.plt.ax.set_xlim(self.mn, self.mx)
                self.kde_xs = np.linspace(self.mn, self.mx, 300)
                self.kde = st.gaussian_kde(y)
                self.plt.ax.plot(self.kde_xs, self.kde.pdf(self.kde_xs), label=self.xlabel)
                self.plt.ax.legend(loc="upper left")
                self.plt.ax.set_title("Histogram")
                self.canvas.draw()   
                
            if self.combo_box_graph.get() == "Scatter Graph":
                self.plt.ax.scatter(self.x_y_range, x, color='r')
                self.plt.ax.scatter(self.x_y_range, y, color='b')
                self.plt.ax.set_title("Scatter Graph")
                self.canvas.draw()  
                
            if self.combo_box_graph.get() == "Select": 
                self.canvas.draw()          

def main(): 
    global root
    root = tk.Tk()
    s = DES("")                        
    s.createFrame(root)
    root.mainloop()
    

if __name__ == '__main__':
    main()
  

So I am wanting to parse the summary value from my Set class to my DES class, adding the summary value to the class self object so that I can view different matplotlib graphs on different windows. At the moment I have it where I call the upload method from my upload_csv class, which gets the use to pick a file, the csv file is read, values are sent to the Set class, the values are then sent to the DES class and are parameters for the set_summary_text function, which is where I want to set the summary and then use the values when I change the combobox bo.所以我想将汇总值从我的集合 class 解析到我的 DES class,将汇总值添加到 class 自身 object 以便我可以在不同的 windows 上查看不同的 matplotlib 图。来自我的 upload_csv class 的方法,它用于选择文件,读取 csv 文件,将值发送到 Set class,然后将值发送到 DES class 并且是 set_summary_text 8834004065 的参数,其中 8988想要设置摘要,然后在我更改 combobox 博时使用这些值。 When the combo box changes to a graph type, the values are then used by matplotlib to plot a graph.当组合框更改为图表类型时,这些值将由 matplotlib 到 plot 图表使用。 The values need to be self values so that I can have multiple graphs and windows. Please help, any questions just ask/这些值需要是自我值,这样我才能有多个图表和 windows。请帮忙,任何问题都可以问/

Since DES canot be a singleton I think you have 3 options here:由于 DES 不能是 singleton,我认为您在这里有 3 个选项:

option 1: using a DES object already created and that already has a summary_output when setting summary选项 1:使用已经创建的 DES object 并且在设置摘要时已经有一个summary_output

class Set:
    def __init__ (self, summary):
        self.summary = summary
        
    def set_summary(self,des):
        print(self.summary)
        des.set_summary_text()

option 2: using a DES object already created when creating the Set object. You have to create a frame for this DES object before using set_summary选项 2:使用在创建 Set object 时已经创建的 DES object。在使用 set_summary 之前,您必须为此 DES object 创建一个帧

class Set:
    def __init__ (self, des, summary):
        self des = des
        self.summary = summary
        
    def set_summary(self):
        print(self.summary)
        self.des.set_summary_text()

option 3: creating a DES object together with the SET object选项 3:与 SET object 一起创建 DES object

class Set:
    def __init__ (self, summary, master):
        self.summary = summary
        self.des = DES(self.summary)
        self.des.createFrame(master)
        
    def set_summary(self):
        print(self.summary)
        self.des.set_summary_text()

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

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