我创建了一个小程序,它显示一个窗口并询问密码id以检查用户是否保存在数据库中。如果密码正确,那么它会影响True
到之前为False
的布尔值mdp_valide
('password_is_valid',英文),并销毁连接窗口。这是一个改变该值的函数,所以我在函数的顶部使用了一个global
语句。然而,当关闭窗口,值mdp_valide
是回False
下面是一些代码,以帮助您了解Python中全局变量的问题
首先,主程序将调用其它功能:
while 1:
mdp_valide, utilisateur_en_cours = fenetre_connection(False, None)
print ('in the main', mdp_valide, utilisateur_en_cours)
if not mdp_valide:
sys.exit()
else :
lancer_messagerie(utilisateur_en_cours)
然后,功能这是不工作:
def fenetre_connection (mdp_val, utilisateur):
mdp_valide = mdp_val
utilisateur_en_cours = utilisateur
root_co = Tk()
# .... Lots of stuff
def verification():
mdp_co = mot_de_passe.get()
global mdp_valide
global utilisateur_en_cours
if mdp_co == recuperer_donnee_utilisateur (identifiant_utilisateur_co, 'mot_de_passe'): # check if the password is the one of the database
print ('condition checked')
mdp_valide = True
utilisateur_en_cours = identifiant_utilisateur_co
print ("before destroying : ", mdp_valide, utilisateur_en_cours)
root_co.destroy()
print ("after destroying : ", mdp_valide, utilisateur_en_cours)
else:
return 1
Button(Frameboutons_co, text="Valider", font='Cambria', command = verification).pack(side=RIGHT) #Bouton qui verifie la validité du pseudo et du mot de passe
root_co.mainloop()
print ('before return : ', mdp_valide)
return mdp_valide
测试:
before destroying: True guil23
after destroying : True guil23
before return : False None
in the main : False None
的问题是在这里:该功能验证()不改变mdp_valide的价值为True
,但返回值后,又回到了False
我不在函数fenetre_connection中看到'global mdp_valide'。这可能是你的问题。 –
呃我删除它,对不起。但它是在原来的帖子。我把它放回去了 – Guil23
实际上,它已经存在了,但你可能被错误的缩进误认为是错误的。我更正了它 – Guil23