所以我做了一个简单的登录和注册页面,一切都很顺利,直到我试图从我的注册页面定义中获取变量。Python说它是一个未解析的引用,它应该解决类型匹配问题,但可能有人可以提供帮助。我也知道有一个更简单的方法来添加页面使用类,但我决定这样做。提前谢谢。p、 s错误出现在sign_up_check()代码中,变量是从sign_up()定义中获取的。在
import tkinter
# window set up
window = tkinter.Tk()
window.geometry("300x200")
window.title("Game")
window.configure(bg="grey26")
# username label
lbl = tkinter.Label(window, text="username", bg="gold")
enter_username = tkinter.Entry(window, bg="indian red1")
lbl.pack()
enter_username.pack()
# password setup
label_password = tkinter.Label(window, text="password", bg="gold")
enter_password = tkinter.Entry(window, bg="indian red1")
label_password.pack()
enter_password.pack()
# sign in
def log_in():
username = enter_username.get()
password = enter_password.get()
if len(username) > 0 and len(password) > 0:
print("it passed")
else:
print("Log in error: Double check username and password")
def sign_up_check():
# init vars
username = signup_username.get()
password = signup_pasword.get()
age = signup_age.get()
# check if vars greater than one
if len(username) > 0 and len(password) > 0 and age > 0:
print("this all passed")
else:
print("all else failed")
def sign_up():
# create new window
window1 = tkinter.Toplevel()
window1.geometry("300x200")
window1.title("Sign up")
window1.configure(bg="grey26")
# create buttons and labels
# username
label_sign_up = tkinter.Label(window1, text="Enter new username", bg="indian red1")
signup_username = tkinter.Entry(window1, bg="gold")
label_sign_up.pack()
signup_username.pack()
# password
label_sign_up_password = tkinter.Label(window1, text="Enter new password", bg="indian red1")
signup_password = tkinter.Entry(window1, bg="gold")
label_sign_up_password.pack()
signup_password.pack()
# age
label_enter_age = tkinter.Label(window1, text="Enter your age", bg="indian red1")
signup_age = tkinter.Entry(window1, bg="gold")
label_enter_age.pack()
signup_age.pack()
# confirm account
button_account = tkinter.Button(window1, text="Create account", bg="red", command=lambda: sign_up_check())
button_account.pack()
# log in button set up
button_login = tkinter.Button(window, text="Log in", bg="gold", command=lambda: log_in())
button_login.pack()
# sign up button
button_signup = tkinter.Button(window, text="Sign up", bg="gold", command=lambda: sign_up())
button_signup.pack()
window.mainloop()
您行为的主要原因是函数中本地定义的变量位于本地范围内。 这意味着它们只能在您的本地功能中使用,而不能在它之外使用。在
正如martineau所指出的,您在函数
sign_up_check
中输入了一个密码错误。在使用全局变量:
你不想使用类的原因是什么?在
老实说,我不认为在编写图形用户界面时使用全局变量和过程编程有任何好处,尤其是使用python。在
我在这里强烈推荐一种面向对象的编程风格,以改善代码的维护并减少冗余编码的数量(开始时的全局声明、每个函数中的全局使用等等)。在
相关问题 更多 >
编程相关推荐