TKinter 进程没有绘制标签、按钮和输入字段...我做错了什么?

发布于 2024-12-05 12:27:35 字数 6548 浏览 0 评论 0原文

我是一名全日制学生,正在上 Python 的第一堂课。 这太奇怪了,它曾经工作过,但现在,它不再显示按钮、标签和输入字段。我确信这是我删除或添加的东西,但是,我不知所措。 有什么想法吗?感谢所有建议。

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()

I'm a full time student, taking my first class in python.
This is so strange, it was working, and now, it is no longer showing the buttons, labels, and entry fields. I'm sure it was something I removed or added, but, I'm at a loss.
Any ideas? All suggestions are appreciated.

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

思念满溢 2024-12-12 12:27:35

您的 main() 函数设置代码无法正常工作。我不确定你之前是如何设置它的,但让它工作的一种方法是这样的:

def main():
    """Run the main program"""
    root = Tk()
    gui = BouncyGUI()
    gui.pack()
    root.mainloop()

Your main() function setup code isn't working properly. I'm not sure how you had it set up before, but one way to get it working is this:

def main():
    """Run the main program"""
    root = Tk()
    gui = BouncyGUI()
    gui.pack()
    root.mainloop()
半﹌身腐败 2024-12-12 12:27:35

您需要对主应用程序进行网格化,而不仅仅是调用其主循环:

def main()
    app = BouncyGUI()
    app.grid()
    app.mainloop()

You need to grid the main app, not just call its mainloop:

def main()
    app = BouncyGUI()
    app.grid()
    app.mainloop()
青巷忧颜 2024-12-12 12:27:35

编译时您的代码有错误:

NameError: global name 'message' is not defined

there is an error in your code when compiling:

NameError: global name 'message' is not defined
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文