I am facing an issue that looks strange to me.
I just want my program to get the data entered by the user in an Entry field and print it in the std out.
for so I use TkInter and an Entry widget, bound to a StringVar and a button to trigger the display.
when I make a single window, that is to say the Entry is in the main window, all runs smoothly.
though, when this very window is displayed after pressing a button on a parent window, things go wrong … the get() on the StringVar looks getting nothing.
As you may see, this is the same code in both cases.
Any ideas ? It looks like a bug, but as I am a bit noob …
Here is my code :
import tkinter as tk
case = 2
def main():
def cb_create():
create()
if case == 1:
main_window = tk.Tk()
w = tk.Button(main_window, text="Create", bg="red", fg="white", width=25, command=cb_create)
w.pack(fill=tk.X, padx=10)
main_window.mainloop()
else:
cb_create()
def create():
window = tk.Tk()
window.config(bg="lightgrey")
s_name = tk.StringVar()
def cb_add():
print(f"<<<{s_name.get()}>>>")
add(s_name.get())
tk.Label(window, text="Name", bg="lightgrey").grid(row=2, column=3, padx=5, pady=5, sticky=tk.E)
tk.Entry(window, bd=3, textvariable=s_name).grid(row=2, column=4, padx=5, pady=5)
tk.Button(window, text="Add", bg="red", fg="white", width=10,
command=cb_add).grid(row=7, column=3, columnspan=2, padx=5, pady=5)
if case == 2:
window.mainloop()
def add(name):
print(f">>>{name}<<<")
if __name__ == '__main__':
main()
Regards !
I have isolated the issue as most as I could in the code, and I tried googling.
“TkInter entry not accessible”, “issue TkInter getting data from Entry”, … (without the quotes of course)
no way
I expect to have the entry value displayed between “>>>” and “<<<” in both cases
value is displayed only in the configuration when the window is the main one.
when the window is a child, no value is displayed “>>><<<“
output in case 2 (right behavior) :
<<<foo>>>
>>>foo<<<
output in case 1 (wrong behavior):
<<<>>>
>>><<<
1