我創建了一個小程序,它顯示一個窗口並詢問密碼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