【问题标题】:In tkinter how do I assign the entry function to a variable在 tkinter 中,如何将入口函数分配给变量
【发布时间】:2015-10-31 04:14:29
【问题描述】:

我试图在 if 语句中使用它来检查用户名是否等于接受的答案。我在我的 ent_username 上使用了 .get() 来尝试选择名称,但它不起作用。是不是它永远不会真正被输入,因为用户名我需要用按钮做更多的代码。请帮忙....

import tkinter
action = ""
#create new window
window = tkinter.Tk()

#name window
window.title("Basic window")

#window sized
window.geometry("250x200")

#creates label then uses ut
lbl = tkinter.Label(window, text="The game of a life time!", bg="#a1dbcd")

#pack label
lbl.pack()

#create username
lbl_username = tkinter.Label(window, text="Username", bg="#a1dbcd")
ent_username = tkinter.Entry(window)

#pack username
lbl_username.pack()
ent_username.pack()
#attempting to get the ent_username info to store
username = ent_username.get()

#configure window
window.configure(background="#a1dbcd")

#basic enter for password
lbl_password = tkinter.Label(window, text="Password", bg="#a1dbcd")
ent_password = tkinter.Entry(window)

#pack password
lbl_password.pack()
ent_password.pack()
#def to check if username is valid
def question():
    if username == "louis":
        print("you know")
    else:
        print("failed")

#will make the sign up button and will call question on click
btn = tkinter.Button(window, text="Sign up", command=lambda: question())

#pack buttons
btn.pack()

#draw window
window.mainloop()

【问题讨论】:

    标签: python user-interface python-3.x tkinter


    【解决方案1】:

    您的问题是您在创建小部件时尝试 get 输入小部件的内容。这将永远是空字符串。您需要在函数内移动.get(),以便在单击按钮时获取值。

    def question():
        username = ent_username.get() # Get value here
        if username == "louis":
            print("you know")
        else:
            print("failed")
    

    if ent_username.get() == "louis":

    您确实可以选择使用 StringVar,但我从来没有发现需要使用它,除非使用 OptionMenu 小部件

    另外,还有一些旁注。使用command参数时,传入变量时只需要lambda,只需确保删除()即可。

    btn = tkinter.Button(window, text="Sign up", command=question)
    

    一个常见的做法是import tkinter as tk。这样,您就不会在所有内容前面加上 tkinter 而是 tk。它只是节省打字和空间。所以看起来是这样的,

    ent_username = tk.Entry(window)
    

    【讨论】:

      【解决方案2】:

      最简单的方法是将变量与 Entry 小部件相关联。对于变量,您必须使用Tkinter variables 之一,并且它必须是与那种小部件关联的 tkinter 变量。对于 Entry 小部件,您需要一个 Stringvar。请参阅 Effbot 的第三方documentation for the Entry widget

      username = tkinter.StringVar()
      ent_password = tkinter.Entry(window, textvariable=username)
      

      在事件处理程序question 中,您可以访问 Tkinter 变量的值。

      if username.get() == name_you_want:
          print "as expected"
      

      正如 Summers 所说,处理函数名称 questioncommand 参数的正确值:

      btn = tkinter.Button(window, text="Sign up", command=question)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        相关资源
        最近更新 更多