首页 > 解决方案 > Tkinter:将文本条目作为按下按钮时调用的函数的参数传递

问题描述

如果问题看起来微不足道,我是 Tkinter 的新手,非常抱歉。我开发了一个 selenium 应用程序,现在我正试图让它与 Tkinter 交互。我在将文本条目作为函数的输入传递时遇到了一些问题:

我定义了登录功能,该功能已经过测试并且可以正常工作:

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

然后我正在创建 GUI,它应该将用户输入的用户名和密码作为 SelfsignIn 函数的参数:

经过一番研究,我想出了这个方法:

    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()

该函数被正确调用,实际上网页打开并执行所有操作,直到需要使用凭据为止。此时,登录文本框未填充 GUI 中给出的输入。

我究竟做错了什么?请随时给我任何建议,在此先感谢。

标签: pythonuser-interfacetkinter

解决方案


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)

推荐阅读