2016-03-12 2 views
0

В этом коде:Атрибут в классе не найден

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. Однако возникает ошибка,

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

Это не работает, потому что 'ButtonBox' не имеет атрибута' encryptButton'. Что ты пытаешься сделать? – zondo

+0

Не могли бы вы также показать код для кнопки. –

+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) 
    …