So, I decided to revamp my coursework app to use OOP for Tkinter and a problem arose.
I use 4 entries for the login screen, 2 for login and 2 for register - each being username and password per side.
Problem I have arose here:
This is my OOP class:
class windowGen:
def __init__(self, master, title, geometry, background):
self.master = master
self.title = title
self.geometry = geometry
self.background = background
master.title(title)
master.geometry(geometry)
master.configure(bg=background)
def createLabel(self, master, contents, fgcolor, bgcolor, horizontal, vertical):
self.label = Label(master, text=contents, justify=LEFT, fg=fgcolor, bg=bgcolor, font="TkFixedFont")
self.label.place(x=horizontal, y=vertical)
def getEntry(self):
return self.entry.get()
def exitWindow(self):
self.master.destroy()
def createEntry(self, master, horizontal, vertical):
self.entry = Entry(master)
self.entry.place(x=horizontal,y=vertical)
Now, the problems are createEntry and getEntry. These work perfect when there is only 1 entry per window, but now I have 4. How do I manage 4 entries when I only use self.entry?
TL;DR: How does one manage entries using OOP Tkinter when you have more than 1 entry box on a window?
Written in Python 3.9.0, latest version of TK and Tcl.
You can use a dictionary to store the created entries using an unique name as the key:
class windowGen:
def __init__(self, master, title, geometry, background):
self.master = master
self.title = title
self.geometry = geometry
self.background = background
master.title(title)
master.geometry(geometry)
master.configure(bg=background)
self.entries = {} # dictionary to store the entries
def createLabel(self, master, contents, fgcolor, bgcolor, horizontal, vertical):
self.label = Label(master, text=contents, justify=LEFT, fg=fgcolor, bg=bgcolor, font="TkFixedFont")
self.label.place(x=horizontal, y=vertical)
def getEntry(self, name): # get value of entry specified by name
return self.entries[name].get()
def exitWindow(self):
self.master.destroy()
def createEntry(self, master, horizontal, vertical, name=None):
entry = Entry(master)
entry.place(x=horizontal,y=vertical)
name = name or str(entry) # use passed name or tkinter internal name
self.entries[name] = entry
return name # return the name as the entry ID
Then you can use the name to access the entry like below:
root = Tk()
gen = windowGen(root, "title", "400x200", "gold")
e1 = gen.createEntry(root, 10, 10)
...
gen.getEntry(e1)