这些线路有什么问题?

2024-09-27 09:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个大型程序中,我有以下几行代码

username = Entry(loginPage)
password = Entry(loginPage)

button1 = Button(loginPage,text = "Login", fg = "red", command = loginClicked(username.get(),password.get()))

当程序运行时,函数loginClicked在开始时运行一次(当字段为空且未单击按钮时),这是它唯一运行的时间。之后,当单击按钮时,该函数根本不运行。函数中的print语句确认了这一点


Tags: 函数代码text程序getusernameloginbutton
1条回答
网友
1楼 · 发布于 2024-09-27 09:25:04

如注释中所述,创建小部件时,在创建小部件之前调用(“运行”)函数,而不是将函数句柄(此处可能是错误的术语)传递给小部件选项command=

这可以通过使用带有lambda的匿名函数来解决:

button1 = Button(root,text = "Login",
                 fg = "red", 
                 command = lambda: loginClicked(username.get(), password.get()))

这将创建一个“扔掉”函数,以输入Tkinter的回调,该回调使用正确的参数调用函数loginClicked()

您还可以阅读effbot.org以了解有关Tkinter回调的更多信息

相关问题 更多 >

    热门问题