简体   繁体   中英

Don't get any value from python tkinter Entry

I have the following:

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.menu()

    def menu(self):
        self.parent.title("Simple menu")
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        configmenu = Menu(menubar, tearoff=0)
        configmenu.add_command(label="Add Player", command=self.addplayer)
        menubar.add_cascade(label="Config", menu=configmenu)
        menubar.add_command(label="Exit", command=self.onexit)

    def onexit(self):
        self.quit()

    def addplayer(self):
        toplevel = Toplevel()
        toplevel.focus_set()
        Label(toplevel, text='first name').grid(row=1, column=0, sticky='W')
        fn = Entry(toplevel, text='first name')
        fn.grid(row=1, column=1, sticky='W')
        indb = insertdb()
        Button(toplevel, text='Save', command=indb.foo(fn.get())).grid(row=4, column=0, pady=1)
        Button(toplevel, text='Abort', command=toplevel.destroy).grid(row=4, column=1, pady=1)


class insertdb():
    def __init__(self):
        # db foo
        return

    def foo(self, fn):
        # toplevel.destroy()
        print(fn)

It's only an example and still not complete. I don't understand,why i do not get any value from fn.get(). After hitting the Save Button, nothing happens.

I'm new myself with tkinter, but perhaps your function is being called at the time the statement is seen by python rather than at run time. I use lambda like this:

x = Button(a, text=c, command=lambda j=c: command(j))  

Maybe you can adjust what I have to your needs.

I'd try defining a separate function for indb.foo(fn.get() , and assigning the function name as the command for the button. You might put it in a try/except format:

def fooget():
    from tkinter import messagebox
    # May need to set nonlocal variable for the Entry here and in addplayer
    try:
        indb.foo(fn.get())
    except:
        messagebox.showerror(message='No luck') # or words to that effect

If you run the script from the command line, it may well give you a helpful error message if it doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM