Tkinter:更新标签内容和按钮命令

时间:2019-03-07 20:44:04

标签: python tkinter label

我有以下代码,但有几个问题。第一个是createUser()命令,将在窗口出现后立即运行。

第二个是我绑定到该命令的按钮本身不会运行该命令(我已经尝试通过将一个简单的字符串打印回IDLE进行测试)。

我最后遇到的问题是,即使将.set()用于命令之外,即使将变量设置为不同的内容,我的标签也不会更新。

root = tk.Tk()
root.title("Sign In Screen")

tk.Label(root,text="Username: ",font="Arial").grid(row=0,column=0)
userIDEntry = tk.Entry(root)
userIDEntry.grid(row=0,column=1)

tk.Label(root,text="Password: ",font="Arial").grid(row=1,column=0)
passwordEntry = tk.Entry(root)
passwordEntry.grid(row=1,column=1)

tk.Label(root,text="Confirm Password: ",font="Arial").grid(row=2,column=0)
passwordConfirm = tk.Entry(root)
passwordConfirm.grid(row=2,column=1)

def createAccount():
    if passwordEntry.get() == passwordConfirm.get():
        exampleFunction() #doesntwork
    else:
        var1.set("Passwords do not match!")
        root.update()

var1 = tk.StringVar()
var1.set("")
tk.Button(root,text="CREATE ACCOUNT",font="Arial",command=createAccount()).grid(row=3,column=0,columnspan=2)
tk.Label(root,textvariable=var1).grid(row=4,column=0,columnspan=2)
root.mainloop()

我希望有人能帮助我,我正在尝试自学Tkinter,并且不能停止遇到诸如此类的小问题。

1 个答案:

答案 0 :(得分:0)

tkinter具有一些特殊的语法(类似于线程)。您应指定command=function command=function()。这将解决您的前两个问题。实际上,在我进行了一些小的调整后,它就可以工作(我认为),也可以完成您想要的变量更新!

import tkinter as tk

root = tk.Tk()
root.title("Sign In Screen")

tk.Label(root, text="Username: ", font="Arial").grid(row=0, column=0)
userIDEntry = tk.Entry(root)
userIDEntry.grid(row=0, column=1)

tk.Label(root, text="Password: ", font="Arial").grid(row=1, column=0)
passwordEntry = tk.Entry(root)
passwordEntry.grid(row=1, column=1)

tk.Label(root, text="Confirm Password: ", font="Arial").grid(row=2, column=0)
passwordConfirm = tk.Entry(root)
passwordConfirm.grid(row=2, column=1)

def createAccount():
    if passwordEntry.get() == passwordConfirm.get():
        print('thing') # your function was not included in post
    else:
        var1.set("Passwords do not match!")
        root.update()

var1 = tk.StringVar()
var1.set("")
tk.Button(root, text="CREATE ACCOUNT", font="Arial", command=createAccount).grid(row=3, column=0, columnspan=2) # removed ()
tk.Label(root, textvariable=var1).grid(row=4, column=0, columnspan=2)
root.mainloop()