Search code examples
pythonooptkinterprocedural-programming

tkinter python and global command


I'm new to python, and i started to use tkinter to build a simple GUI. I was looking around in some examples and i saw that there is a few ways to program with tkinter (or generally program)

The first way is procedural and the recommended way is OOP(correct me if i'm wrong) so here is the question:

assume i got this code and i've imported the library:

root = Tk()
ipLabel = Label(root, text='IP Address:', fg='blue', bg='cyan')
ip = Entry(root)
ipLabel.grid(row=0, column=0)
ip.grid(row=0, column=1, padx=1, pady=3)
root.mainloop()

now since all the code in the global scope i can just access the entry by doing ip.get() from any other function or class

Now let's take the same code in the second way:

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.Widgets()

    def Widgets(self):
        ipLabel = Label(self, text='IP Address:', fg='blue', bg='cyan')
        ip = Entry(self)
        ipLabel.grid(row=0, column=0)
        ip.grid(row=0, column=1, padx=1, pady=3)

MyApp = App()
MyApp.mainloop()

what is the best way to access the ip entry from another class or function? what i tried to do and it's working is just to put global for this variables inside the function

def Widgets(self):
        global ip
        ipLabel = Label(top_frame, text='IP Address:', fg='blue', bg='cyan')
        ip = Entry(top_frame)

I want to know if there is another way to do it and what is the best way to do it?

Thanks in advance


Solution

  • Replace ip with self.ip in App.Widgets(), and then you can access it from elsewhere, e.g. MyApp.ip.