在此代码中:
class ButtonBox(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
shift = tk.Frame(self)
shift.grid(row = 0, column = 0)
shiftLabel = ttk.Label(shift, text = "Shift:")
shiftLabel.grid(row = 0, column = 0)
amountShift = ttk.Entry(shift, width = 5)
amountShift.grid(row = 0, column = 1)
encryptButton = ttk.Button(self, text = "Encrypt")
encryptButton.grid(row = 0, column = 2)
decryptButton = ttk.Button(self, text = "Decrypt")
decryptButton.grid(row = 0, column = 3)
class MainWindow(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.model = Model()
self.UserIO = TextIO(self)
self.UserIO.grid(row = 0, column = 0)
self.Buttons = ButtonBox(self)
self.Buttons.grid(row = 1, column = 0)
self.Buttons.encryptButton.config(command = self.model.encrypt)
self.Buttons.decryptButton.config(command = self.model.decrypt)
def Encrypt():
message = self.UserIO.inputString.get()
shift = int(self.Buttons.shift.get())
self.model.encrypt(message, shift)
def Decrypt():
message = self.UserIO.inputString.get()
shift = int(self.Buttons.shift.get())
self.model.decrypt(message, shift)
root = tk.Tk()
root.resizable(width = False, height = False)
MainWindow(root).pack()
root.mainloop()
我创建一个MainWindow(),然后向Button对象中的Button添加一个命令。但是,它会产生错误,
Traceback (most recent call last):
File "/home/pi/Documents/Code Projects/Caesar Cipher.py", line 120, in <module>
MainWindow(root).pack()
File "/home/pi/Documents/Code Projects/Caesar Cipher.py", line 103, in __init__
self.Buttons.encryptButton.config(command = self.model.encrypt)
AttributeError: 'ButtonBox' object has no attribute 'encryptButton'
,为什么会这样?我创建了一个ButtonBox对象,所以我不明白为什么这不起作用。
答案 0 :(得分:0)
您需要在self.encryptButton
中使用ButtonBox.__init__
而不是encryptButton
。您在encryptButton
函数中创建了一个局部变量__init__
,该变量在外部无法访问。
def __init__(self, parent):
tk.Frame.__init__(self, parent)
…
self.encryptButton = ttk.Button(self, text = "Encrypt")
self.encryptButton.grid(row = 0, column = 2)
…