python - 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 中给出的输入。
我究竟做错了什么?请随时给我任何建议,在此先感谢。
解决方案
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)
推荐阅读
- javascript - 将嵌套对象数组转换为对象数组的最佳方法
- javascript - 有条件地渲染到 div 高度
- python - 有效地遍历多个列表(GPS 坐标)
- octave - 八度查找据称不存在的文件
- python - 将函数返回作为参数传递给另一个函数
- pytorch - CNNLstm 模型的学习率查找器
- asp.net-core - 当有“this”关键字时,如何使用 xUnit 和 Moq 测试 web api 方法
- blockchain - 区块链高清地址如何查询
- reactjs - Typescript React / NestJS 应用程序失败 @Heroku 构建 - “错误 TS2307:找不到模块”
- python - Pycharm Matplotlib 后端不会从 Agg 改变