简体   繁体   中英

Tkinter: Passing text entries as argument of a function called when pressing a button

I am new to Tkinter so sorry if the question looks trivial. I developed a selenium application and now I am trying to make it interactive with Tkinter. I am experiencing some issues to pass text entries as input of a function:

I defined the function to log in, which has been already tested and works properly:

    def SelfsignIn(user,passw):
        browser = webdriver.Firefox(executable_path='C:\Program Files (x86)\geckodriver.exe') (You can find the entire code at the end)
    ....

Then I am creating the GUI which should take username and password typed by the user as argument of the SelfsignIn function:

After some reaserch I come up with this method:

    window = tk.Tk()
    window.title("Login Window")
    greeting = tk.Label(text="Welcome")
    greeting.pack()
    username = tk.Label(text="Username")
    username_entry = tk.Entry()
    password = tk.Label(text="Password")
    password_entry = tk.Entry()
    username.pack()
    username_entry.pack()
    password.pack()
    password_entry.pack()
    par1 = str(username_entry.get())
    par2 = str(password_entry.get())
    button = tk.Button(window, text='Log in', width=25,command=lambda: SelfsignIn(par1,par2))
    button.pack()
    window.mainloop()

The function is called properly, in fact the web page opens and does all operations till when it's time to use the credentials. At this point, the login text boxes are not filled with the input given in the GUI.

What am I doing wrong? Feel free to give me any kind of suggestion, thanks in advance.

You're calling username_entry.get() about a millisecond after creating the entry widget. The user won't have even seen the widget, much less had time to type.

Don't use lambda - call a proper function, and have the function get the data when it is needed and not before. This will make your code easier to write, easier to understand, and easier to maintain.

def signin():
    par1 = str(username_entry.get())
    par2 = str(password_entry.get())
    SelfsignIn(par1, par2)
...
button = tk.Button(window, text='Log in', width=25,command=signin)

Your mistake is, that you take the value of the fields out before the GUI is even displayed, so naturally the two string par1 and par2 will be empty.

You have to get the value inside the entry's when you press the button.

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