Home > Net >  Why these methods are not accessible from Show_Page() method?
Why these methods are not accessible from Show_Page() method?

Time:07-30

Why is it I am not able to access other methods outside Show_Page? Hers's my code below.

class Main:

    style = ttk.Style()
    style.map("C.TButton",
    foreground=[('pressed', 'red'), ('active', 'blue')],
    background=[('pressed', '!disabled', 'black'), ('active', 'white')]
    )

    def selectReports():
        messagebox.showinfo("EDP", "All reports")

    def showReports():
        messagebox.showinfo("EDP", "Select reports")


    def Show_Page():
        program = tk.Tk()
        program.geometry("626x431")
        monitor = ttk.Button(name="",text="Monitor",command=showReports,style="C.TButton")
        monitor.pack(pady=100)
        review = ttk.Button(name="",text="Review",command=selectReports,style="C.TButton")


        review.pack(pady=0)
        # program.withdraw()
        program.mainloop()
    
    # Main method 
    if __name__ == "__main__":
        Show_Page()

This is the following error I am getting. "showReports" is not definedPylancereportUndefinedVariable

CodePudding user response:

showReports is a method of the class, but When you write

monitor = ttk.Button(name="",text="Monitor",command=showReports,style="C.TButton")

python will look for a function in the global namespace, not a method on the object. If you wrote self.showReports python would find the method you want.

Except for another bug in your code. Python requires that an object's "self" reference be included in the method parameter list. This is because methods are just regular python functions with some special sauce added. So, also define your methods as in

    def Show_Page(self):
        program = tk.Tk()
        program.geometry("626x431")
        monitor = ttk.Button(name="",text="Monitor",command=self.showReports,style="C.TButton")
    monitor.pack(pady=100)
        review = ttk.Button(name="",text="Review",command=selectReports,style="C.TButton")
  • Related