0

I am implementing my first Tkinter UI using classes and I am facing some issues with the getter and setter of my Entry.

When I am trying to read the value of "N" i.e. self.nameVar.get(), it prints nothing...

Could anyone point me in the right direction?

Many thanks in advance!

### Class PopUpScreen
class popUpScreen():
    def __init__(self, newContact=True):
        self.root2 = Tk()
        self.root2.title('New Contact')
        self.root2.resizable(False, False)
        self.newContact = newContact
        
        ### Var
        **self.nameVar = StringVar()**
        

        ### Widget
        # Entry
        self.entryFirstName = Entry(self.root2, **textvariable=self.nameVar**)
        
        # Button
        btnSave = ttk.Button(self.root2, text="Save", default="active", command=self.callbackSave).grid(row=9, column=3)
        
        ### Grid
        # Entry
        self.entryFirstName.grid(row=2, column=2, columnspan=2)
        
        # Loop
        self.root2.mainloop()

    def callbackSave(self):
        n = **self.nameVar.get()**
        print('N value: ', n)
        messagebox.showinfo( "Saving...", n))
        self.root2.destroy()
    
### End Popup Contact class
JacksonPro
  • 3,135
  • 2
  • 6
  • 29
Raphael G
  • 9
  • 3

1 Answers1

0

Try this:

from tkinter import messagebox
from tkinter import ttk
import tkinter as tk


class PopUpScreen():
    def __init__(self, new_contact=True):
        self.root2 = tk.Tk()
        self.root2.title("New Contact")
        self.root2.resizable(False, False)
        self.new_contact = new_contact

        self.entry_first_name = tk.Entry(self.root2)
        self.btn_save = ttk.Button(self.root2, text="Save", default="active",
                                   command=self.callback_save)
        self.entry_first_name.grid(row=2, column=2, columnspan=2)
        self.btn_save.grid(row=9, column=3)

        self.root2.mainloop()

    def callback_save(self):
        n = self.entry_first_name.get()
        print("N value: ", n)
        messagebox.showinfo("Saving...", n)
        self.root2.destroy()


PopUpScreen()

If you are going to use entries you don't need tkinter.StringVar because you have <tkinter.Entry>.get() which returns all of the contents of the entry. Also never use variable = <tkinter Widget>(...).grid(...) because the variable will always be None for more info on that read this

TheLizzard
  • 7,248
  • 2
  • 11
  • 31