Процесс TKinter не рисует метки, кнопки и поля ввода ... Что я делаю не так? - PullRequest
0 голосов
/ 19 сентября 2011

Я учусь на дневном отделении и беру свой первый класс по питону. Это так странно, это работало, и теперь больше не отображаются кнопки, метки и поля ввода. Я уверен, что это было то, что я удалил или добавил, но я в растерянности. Есть идеи? Все предложения приветствуются.

from Tkinter import *
import tkFont
import tkMessageBox

class BouncyGUI(Frame):
    """The GUI used to interface with the bouncy calculation from chapter 9 section 1."""

    def __init__(self):
        Frame.__init__(self)

        # Establish the Base Frame
        self.master.title("Calculate the Bounciness of a Ball")
        self.master.rowconfigure(0, weight = 1)
        self.master.columnconfigure(0, weight = 1)
        self.master.grid()
        self.master.resizable(0,0)

        # Establish the components for capturing the Height
        self._heightLabel = Label(self, 
                                  text = "Height of initial drop:",
                                  justify = "left")
        self._heightLabel.grid(row = 0, column = 0)
        self._heightVar = DoubleVar()
        self._heightEntry = Entry(self,
                                  textvariable = self._heightVar, 
                                  justify = "center")
        self._heightEntry.grid(row = 0, column = 1)

        # Establish the "bounciness index"
        self._bouncyIndex = Label(self, 
                                  text = "Bounciness Index:",
                                  justify = "left")
        self._bouncyIndex.grid(row = 1, column = 0)
        self._bouncyVar = DoubleVar()
        self._bouncyEntry = Entry(self,
                                  textvariable = self._bouncyVar,
                                  justify = "center")
        self._bouncyEntry.grid(row = 1, column = 1)
        self._bouncyVar.set(0.6)

        # Establish number of allowable bounces
        self._numberBounces = Label(self, 
                                    text = "Number of Bounces:",
                                    justify = "left")
        self._numberBounces.grid(row = 2, column = 0)
        self._numberBouncesVar = IntVar()
        self._numberBouncesEntry = Entry(self,
                                         textvariable = self._numberBouncesVar,
                                         justify = "center")
        self._numberBouncesEntry.grid(row = 2, column = 1)

        # Establish a field for the response
        self._answer = Label(self, 
                             text = "Distance Travelled",
                             justify = "left")
        self._answer.grid(row = 3, column = 0)
        self._answerVar = DoubleVar()
        self._answerFont = tkFont.Font(weight="bold", size = 12)
        self._answerEntry = Entry(self,
                                 textvariable = self._answerVar,
                                 justify = "center",
                                 font = self._answerFont)
        self._answerEntry.grid(row = 3, column = 1)
        self._answerEntry.config(state = DISABLED, bg = "green")

        # Create frame to hold buttons
        self._buttonFrame = Frame(self)
        self._buttonFrame.grid(row = 4, column = 0, columnspan = 2)

        # Create Reset Button
        self._buttonReset = Button(self._buttonFrame,
                                   text = "Reset",
                                   command = self._reset,
                                   width = 15,
                                   padx = 2,
                                   pady = 2)
        self._buttonReset.grid(row = 0, column = 0)
        #self._buttonReset.config(state = DISABLED)

        # Create Calculate Button
        self._buttonCalc = Button(self._buttonFrame,
                                  text = "Calculate",
                                  command = self._calculate,
                                  width = 15,
                                  padx = 2,
                                  pady = 2)
        self._buttonCalc.grid(row = 0, column = 1)
        #self._buttonCalc.config(state = NORMAL)

    def _reset(self):
        """Allow for the screen to reset for fresh data entry."""
        self._heightVar.set(0.0)
        self._numberBouncesVar.set(0)
        self._answerVar.set(0.0)
        #self._buttonCalc.config(state = NORMAL)
        #self._buttonReset.config(state = DISABLED)
        #self._numberBouncesEntry.config(state = NORMAL)
        #self._bouncyEntry.config(state = NORMAL)
        #self._heightEntry.config(state = NORMAL)

    def _calculate(self):
        """Calculate the bounciness and update the GUI"""
        if self._validDataTypes():
            self._answerVar.set(computeDistance(self._heightVar.get(), \
                                                self._bouncyVar.get(), \
                                                self._numberBouncesVar.get()))
            #self._numberBouncesEntry.config(state = DISABLED)
            #self._bouncyEntry.config(state = DISABLED)
            #self._heightEntry.config(state = DISABLED)
            #self._buttonCalc.config(state = DISABLED)
            #self._buttonReset.config(state = NORMAL)

    def _validDataTypes(self):
        theMessage = ""
        if self._isInt(self._numberBouncesVar.get()) != True:
            theMessage += "Please re-enter Integer Value for Number of Bounces.\n"

        elif self._isFloat(self._bouncyVar.get()) != True:
            theMessage += "Please re-enter Float Value for Bounciness Index.\n"

        elif self._isFloat(self._heightVar.get()) != True:
            theMessage += "Please re-enter Float Value for Initial Height."

        if len(message) > 0:
            tkMessageBox.showerror(message = message, parent = self)
            return False
        else:    
            return True

    def _isInt(self, value):
        # Test to ensure that value entered is an integer
        try:
            x = int(value)
        except ValueError:
            # If not return false
            return False

        # if it is an integer, return true
        return True

    def _isFloat(self, value):
        # Test to ensure that value entered is a float value
        try:
            x = float(value)
        except ValueError:
            # If not return false
            return False

        # If it is a float, return true
        return True

def computeDistance(height, index, bounces):
    """Compute the distance travelled."""
    total = 0
    for x in range(bounces):
        total += height
        height *= index
        total += height
    return total

def main():
    """Run the main program"""
    BouncyGUI().mainloop()

main()

Ответы [ 3 ]

1 голос
/ 19 сентября 2011

Ваш код установки функции main() не работает должным образом. Я не уверен, как вы настроили его раньше, но один из способов заставить его работать так:

def main():
    """Run the main program"""
    root = Tk()
    gui = BouncyGUI()
    gui.pack()
    root.mainloop()
0 голосов
/ 20 сентября 2011

Вам нужно создать сетку основного приложения, а не просто вызвать его mainloop:

def main()
    app = BouncyGUI()
    app.grid()
    app.mainloop()
0 голосов
/ 19 сентября 2011

в вашем коде ошибка при компиляции:

NameError: global name 'message' is not defined
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...