2015-03-01 5 views
-1

Я создаю программу Python tkinter, которая позволяет пользователю вводить значение. Затем пользователь выберет опции, которые включают в себя по Фаренгейту или Цельсию с помощью переключателей. Появится сообщение, которое выбирает пользователь, который выбрал выбор, и нажав кнопку расчета, новое преобразованное значение Фаренгейта или Цельсия будет отображаться на этикетке за кнопкой «Вычислить». Я строю базу программы на View Model Control, и когда я выполнить основную программу, которая программа управления Я следовал за ошибки:Ошибка Python tkinter program

AttributeError: 'Calculate' object has no attribute 'radioButtonShowChoice' 

У меня есть 3 отдельные файлы, которые для архитектуры View Модель управления флиртует один с именем кадра для просмотра:

import tkinter 
class AppFrame(tkinter.Frame): 
    """ 
    class AppFrame is the View for a simple program converts between temperature 
    in Fareinheit and tempterature in Celicus 
    """ 
    def __init__(self, controller): 
     tkinter.Frame.__init__(self) # initializes the superclass 
     self.pack() # required in order for the Buttons to show up properly 
     self.controller = controller 
     v = tkinter.IntVar() 
     self.titleLabel1 = tkinter.Label(self) 
     self.titleLabel1["text"] = "Fahrenheit and Celcius converter program" 
     self.titleLabel1.pack() 

     self.titleLabel2 = tkinter.Label(self) 
     self.titleLabel2["text"] = "Enter your value here:" 
     self.titleLabel2.pack({"fill":"x","padx":"10"}) 

     self.entryData = tkinter.Entry(self) 
     self.entryData.pack({"fill":"x","padx":"10"}) 

     self.titleLabel3 = tkinter.Label(self) 
     self.titleLabel3["text"] = "Choose options bellow:" 
     self.titleLabel3.pack({"fill":"x","padx":"10"}) 

     self.radioButton1 = tkinter.Radiobutton(self,text="Fahreinheit", variable = v, value =1) 
     self.radioButton1["command"] = self.controller.radioButtonShowChoice 
     self.radioButton1.pack({"anchor":"w"}) 

     self.radioButton2 = tkinter.Radiobutton(self,text="Celcius", variable = v, value = 2) 
     self.radioButton2["command"] = self.controller.radioButtonShowChoice 
     self.radioButton2.pack({"anchor":"w"}) 

     self.resultLabel1 = tkinter.Label(self) 
     self.titleLabel1.pack({"fill":"x","padx":"10"}) 

     self.calculateButton = tkinter.Button(self) 
     self.calculateButton["text"] = "CALCULATE" 
     self.calculateButton["command"] = self.controller.buttonCalculate 
     self.calculateButton.pack({"fill":"x","padx":"10"}) 

     self.resultLabel2 = tkinter.Label(self) 
     self.titleLabel2.pack({"fill":"x","padx":"10"}) 

Второй один называется высчитывает для модели

import tkinter 
import frame 
class Calculate: 
    """ 
    Class Calculate is the Model for calculating the convert to Fahreinheit or Celcius 
    It also displays the result on the screen 
    """ 
    def __init__(self): 
     self.newValue = 0 
     self.view = frame.AppFrame(self) 

    def displayChoice(self): 
     if str(self.view.v.get()) == "1": 
      return "You chose option 1 for Fahreinheit converter" 
     elif str(self.view.v.get()) == "2": 
      return "You chose option 2 for Celcius converter" 

    def displayResult(self): 
     if str(self.view.v.get()) == "1": 
      self.newValue = (9/5 * int(self.view.entryData.get())) + 32 
     elif str(self.view.v.get()) == "2": 
      self.newValue = 5/9 * (int(self.view.entryData.get()) - 32) 

    def __str__(self): 
     return str(self.newValue) 

последний является основным пр ogram который называется myMain для контроллера

import tkinter 
import frame 
import calculate 

class Display: 
    """ 
    The Display class for an app that follows the Model/View/Controller architecture. 
    When the user presses the Button converter on the View, this Display calles the appropriate methods in the Model. 
    """ 
    def __init__(self):  
     root = tkinter.Tk() 
     self.model = calculate.Calculate() 
     self.view = frame.AppFrame(self) 
     self.view.mainloop() 
     root.destroy() 

    def radioButtonShowChoice(self): 
     self.view.resultlabel1["text"] = self.model.displayChoice 

    def buttonCalculate(self): 
     self.model.displayResult() 
     self.view.resultLabel2["text"] = "The new value of tempreature is "+str(self.model 
if __name__ == "__main__": 
    d = Display() 

Любой помогает сделать эту программу работы будут оценены Благодаря

ответ

1

В Display.__init__(self)

self.model = calculate.Calculate() 

В Calculate.__init__(self)

self.view = frame.AppFrame(self) 

В AppFrame.__init__(self, controller)

self.controller = controller 
... 

self.radioButton1["command"] = self.controller.radioButtonShowChoice 
self.radioButton2["command"] = self.controller.radioButtonShowChoice 

self.controller это значение, переданное в AppFrame конструктор, который был объектом Вычислить. Вы пытаетесь назначить radioButtonShowChoice, который не является атрибутом в Calculate, как указывает сообщение об ошибке. Я предполагаю, что вы хотите назначить функцию от Display. Вы также создаете два AppFrame, которые меня сбивают с толку - один в объекте Calculate и один в объекте Display.

В вашей реализации, AppFrame нуждается в функции от Display, так AppFrame в какой-то момент необходима ссылка на Display - первое созданное внутри Calculate не имеет этой ссылки.

Calculate - AppFrame instance #1 
Display - AppFrame instance #2, Calculate object 
AppFrame #1 - Calculate as the controller 
AppFrame #2 - Display as the controller 

Наконец, где-то с этим сообщением об ошибке должно быть трассировка стека, указывающая на номер строки, в которой произошла ошибка. То есть действительно важное.