为什么If语句不能与tkinter一起工作



我创建了两个py文件,一个保存登录GUI,另一个包含了一堆函数和窗口,我称之为终端。

我正在尝试做以下事情:首先显示登录GUI窗口,然后输入正确的凭据才能打开/运行终端(第二个GUI窗口)。

然而,无论我尝试什么,我都没有得到凭证后打开的第二个窗口。我尝试过使用if语句,但是失败了,我唯一想到的是在一个文件中重新做整个代码,这似乎不是一个好主意,在一个文件中有那么多代码

登录GUI:

import tkinter as tk

# from tkinter_practice import *

def username(txt_username):
if txt_username == "1":
return True

def password(txt_password):
if txt_password == "2":
return True

def ok_button(gotten_username, gotten_password):
if username(gotten_username) and password(gotten_password):
print('login success')
return True
else:
print('Incorrect Username or Password')
return False

root2 = tk.Tk()
root2.title('Login window')
root2.geometry('400x200-550-400')
root2.columnconfigure(0, weight=1)
root2.columnconfigure(1, weight=1)
root2.columnconfigure(2, weight=1)
root2.rowconfigure(0, weight=1)
root2.rowconfigure(1, weight=1)
root2.rowconfigure(2, weight=1)
lbl_username = tk.Label(root2, text='Username')
lbl_username.grid(row=1, column=0)
ent_username = tk.Entry(root2)
ent_username.grid(row=1, column=1)
lbl_password = tk.Label(root2, text='Password')
lbl_password.grid(row=2, column=0, sticky='n')
ent_password = tk.Entry(root2)
ent_password.grid(row=2, column=1, sticky='n')

btn_ok = tk.Button(root2, text='LOGIN', command=lambda: ok_button(ent_username.get(), ent_password.get()), padx=10,
pady=5)
btn_ok.grid(row=3, column=1, sticky='nw', )
btn_cancel = tk.Button(root2, text='Cancel', command=quit, padx=10, pady=5)
btn_cancel.grid(row=3, column=1, sticky='n')
root2.mainloop()

和第二部分代码,其中包含第二个窗口/GUI,我将在第一个凭据为True后打开:

import tkinter as tk
from tkinter import *
# from PIL import ImageTk, Image
import webbrowser
import pytz
import datetime
import login_GUI
# from tkinter import messagebox
# Main frame/window
if login_GUI.ok_button(login_GUI.ent_username.get, login_GUI.ent_password.get):
root = tk.Tk()
root.title("Main terminal")
root.geometry("800x600-50-50")
# Here I get the icon for the left corner of bar on top
root.iconbitmap(icon)
new = 1
url = "https://www.youtube.com"
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.columnconfigure(2, weight=1)


root.mainloop()

您应该将主代码块放在login_GUI.py内部的函数中,例如login(),然后在函数结束时返回凭据验证结果。

login_GUI.py:

import tkinter as tk
def login():
validated = False   # credential validation result
def username(txt_username):
if txt_username == "1":
return True
def password(txt_password):
if txt_password == "2":
return True
def ok_button(gotten_username, gotten_password):
nonlocal validated
if username(gotten_username) and password(gotten_password):
print('login success')
validated = True  # validation successful
root2.destroy() # close the login window
else:
print('Incorrect Username or Password')
root2 = tk.Tk()
...
root2.mainloop()
return validated

那么你可以使用login_GUI.login():

import login_GUI
if login_GUI.login():
...

最新更新