Home > front end >  Python Tkinter: What syntax in main() will get the return value of a method bound to button in a cla
Python Tkinter: What syntax in main() will get the return value of a method bound to button in a cla

Time:01-14

New to tkinter, I want a short program to:

  • create a window to take user input, by means of an entry widget and a submit button
  • capture the input and return it to main, so that I can do something else with it.

The following code creates the window and captures input, but breaks at the next-to-last line.

from tkinter import *
from tkinter import ttk


class TxtEntryWindow:

    def __init__(self):
        self.root = Tk()
        self.frame = ttk.Frame(self.root).pack()
        self.box = ttk.Entry(self.frame)
        self.box.pack()
        self.but = ttk.Button(self.frame, text='Submit', command=self.capture_txt)
        self.but.pack()
        self.root.mainloop()
        
    def capture_txt(self):
        txt = self.box.get()
        return txt


win = TxtEntryWindow()
user_input = win.capture_txt()
print(user_input)

Here's a copy of the error message:

Traceback (most recent call last):

File "C:...\wclass.py", line 22, in user_input = win.capture_txt() File "C:...\wclass.py", line 17, in capture_txt txt = self.box.get() File "C:...\Python\Python310\lib\tkinter_init_.py", line 3072, in get return self.tk.call(self._w, 'get') _tkinter.TclError: invalid command name ".!entry"

I have no idea what this means. I suspect that dependence of "txt" on the button event in the class prevents "win.capture_txt()" in main() at the bottom from fetching the user input. Can anyone shed light?

Consulted Python's official documentation (unintelligible), Tkinter's official tutorial and command reference. Searched numerous analogies on StackOverflow and on youtube. Googled the error message itself. I've tried to strike out on my own and rewrite the critical command about twenty times. Blind intuition leads nowhere. Stabbing in the dark.

CodePudding user response:

The error means that the entry widget (self.box) has been destroyed when the line user_input = win.capture_txt() is executed.

You can use an instance variable to store the input text instead and access this instance variable after the window is destroyed:

from tkinter import *
from tkinter import ttk


class TxtEntryWindow:

    def __init__(self):
        self.text = "" # initialize the instance variable
        self.root = Tk()
        self.frame = ttk.Frame(self.root).pack()
        self.box = ttk.Entry(self.frame)
        self.box.pack()
        self.but = ttk.Button(self.frame, text='Submit', command=self.capture_txt)
        self.but.pack()
        self.root.mainloop()

    def capture_txt(self):
        # save the user input into the instance variable
        self.text = self.box.get()
        self.root.destroy()


win = TxtEntryWindow()
print(win.text) # show the content of the instance variable
  • Related