I'm learning to code a program with GUI, but I can't get my head around with the best principle.
At the moment I'm trying to have 5 entries and the text which would be written to entries would automatically update to labels. Here is my code so far:
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
# GUI starts here
self.label = tk.Label(parent, text="Give values")
self.label.grid(row="1")
self.entries()
self.labels()
def entries(self):
for i in range(5):
number1 = tk.StringVar()
entry = tk.Entry(textvariable=number1)
entry.grid(row=3, column=i)
result = entry.get()
return result
def labels(self,):
for i in range(5):
label = tk.Label(self.parent, text=self.entries(), width=17, borderwidth=2, relief="groove")
label.grid(row=4, column=i)
if __name__ == "__main__":
root = tk.Tk()
root.geometry("1280x800")
MainApplication(root).grid()
root.mainloop()
The output of my code is following. Apparently, lots of things are wrong because I don't get five entry boxes and they don't update to labels below automatically.
I have two questions:
If you want labels to have exactly the same text as the entry widgets, the simplest solution by far is to have them share the same textvariable
.
Here is a basic example. When you run it and then type into any entry, the value is immediately displayed in the label below it.
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self,parent, *args, **kwargs)
self.parent = parent
self.label = tk.Label(parent, text="Give values")
self.label.grid(row=1)
for column in range(5):
var = tk.StringVar()
entry = tk.Entry(root, textvariable=var)
label = tk.Label(root, textvariable=var, width=17)
entry.grid(row=2, column=column, sticky="ew")
label.grid(row=3, column=column, sticky="ew")
if __name__ == "__main__":
root = tk.Tk()
root.geometry("1280x800")
MainApplication(root).grid()
root.mainloop()
I don't normally advocate for using the special tkinter variables for Entry
widgets, but this is a good example of when it is the right tool for the job.
As for the question about using nested classes, no, they wouldn't help. There is almost never a time when nested classes are better than defining classes at the global scope. The nesting makes the code more complicated to write and to understand while providing very little extra value.
Nested classes can be useful in very specific instances, but shouldn't normally be used.