Search code examples
pythonpython-3.xtkintertkinter-entry

Read the transfer value from e1=Entry(root) and take it with you into the new function


def fahrradfuerhrdoku ():
        print (e1.get())
        
        
def button_searchdata():
        root = Tk()
        root.eval('tk::PlaceWindow . center')
        root.geometry('400x200')
        command=create_window
        root.title("Fahrradsuche für HR Doku")
        Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
        e1 = Entry(root)
        e1.place(x = 150, y = 80, width=200, height=30)
        Button(root, text='suchen', command=fahrradfuerhrdoku).grid(row=3, column=1, sticky=W, pady=4)
        root.mainloop()

I am trying to ensure that when a user makes an entry via e1 = Entry "e.g. 123456", the "Fahrradfuerhrdoku" function receives the value "123456" and I can continue working with it in the function.

However, when I run print (e1.get()) in the function above, Python tells me that e1 is undefined. I thought it has the value that is entered by entry.


Solution

  • you can make the e1 variable global in the function so you can use it outside of the function , like this:

    def fahrradfuerhrdoku ():
            print (e1.get())
            
            
    def button_searchdata():
            #makes e1 global
            global e1
            root = Tk()
            root.eval('tk::PlaceWindow . center')
            root.geometry('400x200')
            root.title("Fahrradsuche für HR Doku")
            Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
            e1 = Entry(root)
            e1.place(x = 150, y = 80, width=200, height=30)
            Button(root, text='suchen', command=fahrradfuerhrdoku).grid(row=3, column=1, sticky=W, pady=4)
            root.mainloop()
    

    or you need to put e1 out of the function so its reachable by the function 'fahrradfuerhrdoku' , like this :

    def fahrradfuerhrdoku ():
            print (e1.get())
            
            
    def button_searchdata():
            root.eval('tk::PlaceWindow . center')
            root.geometry('400x200')
            root.title("Fahrradsuche für HR Doku")
            Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
            Button(root, text='suchen', command=fahrradfuerhrdoku).grid(row=3, column=1, sticky=W, pady=4)
            root.mainloop()
    
    root = Tk()
    e1 = Entry(root)
    e1.place(x = 150, y = 80, width=200, height=30)