Getting an entry from a child window?

495 views Asked by At

For some reason i can't get the entry from the child window. I want to get the entry from the child window and then graph a rectangle. The error that i get is: x=float(self.txtSide.get()) AttributeError: 'MainWindow' object has no attribute 'txtSide'

import tkinter as tk
import turtle
tu=turtle


class MainWindow(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Cupe",command=self.Cupe)
        self.button.pack(side="top")

    def Cupe(self):

        c = tk.Toplevel(self)
        c.wm_title("Cupe")

        lab=tk.Label(c,text="Side")
        lab.pack()

        c.txtSide=tk.Entry(c)
        c.txtSide.pack()


        button=tk.Button(c,text="Graph",command=self.graphCupe)
        button.pack(side="bottom")


    def graphCupe(self):
        x=float(self.txtSide.get())
        tu.forward(x)
        tu.left(90)
        tu.forward(x)
        tu.left(90)
        tu.forward(x)
        tu.left(90)
        tu.forward(x)

if __name__ == "__main__":
    root = tk.Tk()
    main = MainWindow(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()
1

There are 1 answers

2
David Reeve On

The problem is that self in graphCupe refers to the MainWindow instance, and not to the child window. You would need to pass the child window into the graphCupe function. This would be one way to do it:

    def Cupe(self):
        ...
        button=tk.Button(c,text="Graph",command=lambda: self.graphCupe(c))
        button.pack(side="bottom")

    def graphCupe(self,window):
        x=float(window.txtSide.get())
        ...

Now the graphCupe function takes the window it needs to operate on, and the button calls the function and passes it its child window.