简体   繁体   English

Python 使用 tkinter 命令按钮传递参数

[英]Python Pass Parameters using tkinter command button

I am creating a login system, where a user enters a password and username, and on a button being pressed, it goes to the function to check the password.我正在创建一个登录系统,用户输入密码和用户名,按下按钮后,它会转到 function 以检查密码。

from tkinter import *

def login():
    Usr = Tk()
    Usr.title("Login")
    Usr.geometry("200x150+860+400")
    Usr.configure(bg="grey22")
    usrBox = Label(Usr, text = "Username:", font=( "arial",12, "bold"), fg="white", bg="grey22").place(x=50, y=10)
    passbox = Label(Usr, text = "Password:", font=( "arial",12, "bold"), fg="white", bg="grey22").place(x=50, y=60)
    usrName = StringVar()
    usernameInput = ""
    passwordInput = ""
    PssWord = StringVar()
    usrName = Entry(Usr, textvariable= usernameInput, width=15, bg="lightgrey").place(x=50, y=37)
    PssWord = Entry(Usr, textvariable= passwordInput, width=15, bg="lightgrey").place(x=50, y=87)
    enter = Button(Usr, text = "login", width=11, height = 1, bg="lightgrey", activebackground="grey", font=("arial", 10, "bold"), command = checkPassword: action(usernameInput, passwordInput)).place(x=50, y=110)
    Usr.mainloop()
def checkPassword(usernameInput, passwordInput):
    print(usernameInput, passwordInput)

login()

The action returns invalid syntax该操作返回无效语法

There are multiple problems with your code:您的代码存在多个问题:

  • You have to create a lambda calling the checkPassword function.您必须创建一个lambda调用checkPassword function。
  • You create some StringVar , but then pass plain strings to the Entry fields and use them in the callback;您创建一些StringVar ,然后将纯字符串传递给 Entry 字段并在回调中使用它们; those will not get updated with the actual values, use the StringVar instead.那些不会用实际值更新,请改用StringVar
  • If you do x = Widget(...).layout(...) , then x is not the widget but None , which is the result of all the layout functions ( pack , grid , place , etc.), this is not a problem here, though, as you do not use all those variables anyway如果您执行x = Widget(...).layout(...) ,则x不是小部件而是None ,这是所有布局功能( packgridplace等)的结果,这是不过,这不是问题,因为无论如何您都不会使用所有这些变量

Fixed code (excerpt)固定代码(摘录)

usernameInput = StringVar()
passwordInput = StringVar()
Entry(Usr, textvariable=usernameInput, ...).place(x=50, y=37)
Entry(Usr, textvariable=passwordInput, ...).place(x=50, y=87)
Button(Usr, text="login", ..., command=lambda: checkPassword(usernameInput, passwordInput)).place(x=50, y=110)

Then, in the checkPassword function, use StringVar.get() to get the actual values.然后,在checkPassword function 中,使用StringVar.get()获取实际值。

You can use:您可以使用:

usrName = Entry(Usr, bd=3)
usrName.place(x=75, y=35)
enter = Button(Usr, text="Send", width=15, height=2,
       command=lambda: checkPassword(usrName.get()))
enter.place(x=25, y=75)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM