1 回答
TA贡献1757条经验 获得超8个赞
我制作 Tkinter 界面已有 2 年了,现在。我最初面临同样的问题。根据我的经验,我建议您定义一个继承Tk根小部件的类,然后将元素小部件指定为该类的属性,并将回调函数指定为该类的函数。这将使访问全局小部件(按钮)和功能变得容易。这些小部件和函数在类定义中是全局的。它使它们易于访问。您可以按照以下模板
from tkinter import *
class Interface(Tk):
def __init__(self, title):
Tk.__init__(self)
self.title(title)
self.build()
def build(self):
self.UserNameLabel = Label(self, text="User Name")
self.UserNameLabel.grid(row=0, column=0, sticky=E, pady=10)
self.UserNameEntry = Entry(self)
self.UserNameEntry.grid(row=0, column=1, sticky=W, pady=10)
self.PassWordLabel = Label(self, text="Password")
self.PassWordLabel.grid(row=1, column=0, sticky=E, pady=10)
self.PassWordEntry = Entry(self, show='*')
self.PassWordEntry.grid(row=1, column=1, sticky=W, pady=10)
self.status = Label(self, text='Please enter User Name and Password')
self.status.grid(row=2, column=0, columnspan=2, pady=10)
self.LoginButton = Button(self, text='Login', width=20, command=self.checkCreadentials)
self.LoginButton.grid(row=3, column=0, columnspan=2, pady=10)
def checkCreadentials(self):
if (self.UserNameEntry.get().strip() == 'username') and (self.PassWordEntry.get()=='password'):
self.status['text']= 'Welcome !'
else:
self.status['text']= 'Invalid User Name or Password!!!'
self.bell()
Interface('Login').mainloop()
添加回答
举报