Try_Learning
Try_Learning

Reputation: 31

Global name 'root not defined', tkinter, python

Very new to python and wanted to create a GUI window that i plan to use for a Query tool later. I keep getting global name root not defined error. I am trying to create a user interface that has a window. I probably am missing Object concepts. Need some help. Thanks. Here is my code:

from Tkinter import *


class GUI(Frame):
"""A Graphical User Interface Class for building a GUI Frame.

Attributes:
    master : 
"""

    def __init__(self,master):
        Frame.__init__(self,master)
        self.grid()
        self.menubar()
        self.label()
        self.onExit()


    def menubar(self):
        self.menubar = Menu(root)
        self.menubar.add_command(label="File")
        self.menubar.add_command(label="Exit", command=self.onExit)
        root.config(menu=self.menubar)


    def label(self):
        L0 = Label(text="Use this tool to find the lake location.").grid(row = 0, column = 0)
        L1 = Label(text="Lake name :").grid(row = 2)
        L2 = Label(text="County name :").grid(row = 3)

        E0 = Entry().grid(row = 2, column = 2)
        E1 = Entry().grid(row = 3, column = 2)

        B0 = Button(text="Search").grid(row = 6, column = 2)

        if self.E0 and self.E1==null:
            raise RuntimeError('Entry cannot be blank.')


    def onExit(self):
        self.quit()

def main():
    root = Tk()
    root.geometry("400x200")
    root.title(" Locator (L^3)")
    app = GUI(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Upvotes: 0

Views: 4422

Answers (1)

TankorSmash
TankorSmash

Reputation: 12747

def menubar(self):
    self.menubar = Menu(root)
    self.menubar.add_command(label="File")
    self.menubar.add_command(label="Exit", command=self.onExit)
    root.config(menu=self.menubar)

root doesn't exist here. You either need to make root a global variable (bad idea) or pass root to the GUI class and save a reference to it.

Something like

def __init__(self, master):
    Frame.__init__(self, master)
    self.master = master
    self.grid()
    self.menubar()
    self.label()
    self.onExit()

def menubar(self):
    self.menubar = Menu(self.master)
    self.menubar.add_command(label="File")
    self.menubar.add_command(label="Exit", command=self.onExit)
    self.master.config(menu=self.menubar)

Upvotes: 2

Related Questions