我正在制作一个小而无用的登录系统,只是为了测试python和Tkinter。我的代码是:
from tkinter import *
import ctypes
def mbox(title, text):
ctypes.windll.user32.MessageBoxA(0, text, title, 0)
def login():
if entry_1 == "admin" and entry_2 == "admin":
mbox("Success!", "Login successful!")
else:
mbox("Sorry...", "Login unsuccessful.")
root = Tk()
label_1 = Label(root, text="Name")
label_2 = Label(root, text="Pass")
entry_1 = Entry(root)
entry_2 = Entry(root)
button_1 = Button(root, text="Login", command=login)
label_1.grid(row=0)
label_2.grid(row=1)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
button_1.grid(row=2, column=0, rowspan=2)
root.mainloop()
然而,当我运行此代码并单击按钮时,mbox显示为标题:'S'和文本:'L'
老实说,我不确定为什么会发生这种情况,我的def设置错了吗?
答案 0 :(得分:1)
您发布为“已修复”的代码无效。 entry_1
和entry_2
是小部件,没有值。要在输入框中输入文字,您需要使用entry_1.get()
和entry_2.get()
。另外我建议使用字典检查用户名和密码,就像这篇文章一样。你的代码看起来像这样:
import tkinter as tk
import tkinter.messagebox
Dict={"admin":"admin"}
def mbox(title, text):
tk.messagebox.showinfo(title, text)
def login():
if entry_1.get() in Dict and Dict[entry_1.get()] == entry_2.get():
mbox("Success!", "Login successful!")
else:
mbox("Sorry...", "Login unsuccessful.")
root = tk.Tk()
label_1 = tk.Label(root, text="Name")
label_2 = tk.Label(root, text="Pass")
entry_1 = tk.Entry(root)
entry_2 = tk.Entry(root)
button_1 = tk.Button(root, text="Login", command=login)
label_1.grid(row=0)
label_2.grid(row=1)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
button_1.grid(row=2, column=0, rowspan=2)
root.mainloop()
答案 1 :(得分:-1)
我设法修复了代码,同时接受了您的建议:
import tkinter as tk
import tkinter.messagebox
def mbox(title, text):
tk.messagebox.showinfo(title, text)
def login():
if entry_1.get() == "admin" and entry_2.get() == "admin":
mbox("Success!", "Login successful!")
else:
mbox("Sorry...", "Login unsuccessful.")
root = tk.Tk()
label_1 = tk.Label(root, text="Name")
label_2 = tk.Label(root, text="Pass")
entry_1 = tk.Entry(root)
entry_2 = tk.Entry(root)
button_1 = tk.Button(root, text="Login", command=login)
label_1.grid(row=0)
label_2.grid(row=1)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
button_1.grid(row=2, column=0, rowspan=2)
root.mainloop()
谢谢你们,'帮助!