我的代码出现了两个不同的问题
首先,我无法显示网格的第四行,尽管第五行似乎显示得很好。
其次,我的 passVal 函数一直给我错误:
passVal() takes 1 positional argument but 2 were given
我试过重新排列并将其转换为字符串,但似乎没有任何效果。
我认为可能是一件事导致了同样的问题,因为它们都以同一个按钮为中心,但我不确定。
import tkinter
class AccountCreation:
def __init__(self):
self.main = tkinter.Tk()
self.main.title("Account Creation")
self.topleftLabel = tkinter.Label(text=" ")
self.topleftLabel.grid(row=1,column=1)
self.botrightLabel = tkinter.Label(text=" ")
self.botrightLabel.grid(row=5,column=5)
self.promptLabel = tkinter.Label(text="Create a password with at least nine (9)\n characters that contains at least one digit, \n one uppercase, and one lowercase letter.\n\n")
self.promptLabel.grid(row=2,column=2,columnspan=2)
self.passLabel = tkinter.Label(text="Password:")
self.passLabel.grid(row=3,column=2)
self.passEntry = tkinter.Entry(width = 18, justify='right')
self.passEntry.grid(row=3,column=3)
self.enterButton = tkinter.Button(text="Enter", \
command=self.passVal(self.passEntry.get()))
self.enterButton.grid(row=4,column=2)
self.cancelButton = tkinter.Button(text="Cancel", \
command=self.cancel)
self.cancelButton.grid(row=4,column=3)
tkinter.mainloop()
def passVal(pw):
if len(pw) < 9:
print ("no")
def cancel(self):
self.main.destroy()
my_gui = AccountCreation()
请您参考如下方法:
除了您遇到的缩进问题之外,类中的所有方法都需要将 self 作为第一个参数传递,除非您使用可以使其成为独立函数的特殊标记。
改变:
def passVal(pw):
收件人:
def passVal(self, pw):
您还需要更改 Enter 按钮上的命令以使用 lambda 以防止 python 在启动时调用 passVal 方法。
改变:
command=self.passVal(self.passEntry.get())
收件人:
command=lambda: self.passVal(self.passEntry.get())
您真的不需要在这里使用 lambda,甚至不需要传递 self.passEntry.get() 的参数。您可以使用 self.passEntry.get() 而不是 pw 来获取 passVal() 方法中输入字段的值。
如果你改变这个:
command=lambda: self.passVal(self.passEntry.get())
对此:
command=self.passVal
还有这个:
def passVal(self, pw):
if len(pw) < 9:
print ("no")
对此:
def passVal(self):
if len(self.passEntry.get()) < 9:
print ("no")
您的程序将运行良好,您可以避免在命令中使用 lambda。
注意:您不需要使用标签作为间隔物。您可以在网格放置中简单地使用 padx 和 pady。
看看下面的代码:
import tkinter
class AccountCreation:
def __init__(self):
self.main = tkinter.Tk()
self.main.title("Account Creation")
self.promptLabel = tkinter.Label(text="Create a password with at least nine (9)\n characters that contains at least one digit, \n one uppercase, and one lowercase letter.\n\n")
self.promptLabel.grid(row=2,column=2,columnspan=2,pady=(10,10))
self.passLabel = tkinter.Label(text="Password:")
self.passLabel.grid(row=3,column=2)
self.passEntry = tkinter.Entry(width = 18, justify='right')
self.passEntry.grid(row=3,column=3)
self.enterButton = tkinter.Button(text="Enter", \
command=self.passVal(self.passEntry.get()))
self.enterButton.grid(row=4,column=2)
self.cancelButton = tkinter.Button(text="Cancel", \
command=self.cancel)
self.cancelButton.grid(row=4,column=3,pady=(10,10))
tkinter.mainloop()
def passVal(self, pw):
if len(pw) < 9:
print ("no")
def cancel(self):
self.main.destroy()
my_gui = AccountCreation()
请注意,使用 pady=(10,10) 很简单,我们在小部件的顶部和底部放置了空间。
