Python百分比计算器

时间:2017-09-23 03:17:44

标签: python tkinter

我在使用此代码计算百分比方面遇到了一些麻烦。它在计算中显示错误消息,但我不知道如何显示结果。这是我的代码:

from tkinter import*
import math


class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.widget()


    def widget(self):
        self.ori = Label(self, text ="Insira o número desejado: ")
        self.ori.grid(row = 1, column = 0, columnspan = 2, sticky =W)

        self.ori2 = Label(self, text ="Insira a porcentagem desejada: ")
        self.ori2.grid(row = 2, column = 0, columnspan = 2, sticky =W)

        self.num =float(Entry.cget(self))
        self.num.grid(row = 1, column = 2, sticky =E)

        self.num1 =float(Entry.cget()get(self))
        self.num1.grid(row = 2, column = 2, sticky =E)

        self.label = Label(self, text="A porcentagem do número selecionado é: ")
        self.label.grid(row=3, column=0, columnspan=2, sticky=W)

        btstart = Button(self, text="Calcular", width=7, command=self.cal)
        btstart.grid(row = 5,column =1)

        btstop = Button(self, text="Sair", width=7, command=self.close_window)
        btstop.grid(row = 5,column =2)


    def cal(self):
        self.calc = math(self.num * self.num1) / 100
        print(self.cal)


    def close_window(Application):
        root.destroy()


root = Tk()
root.title("Programa de calculo")
root.geometry("400x150")

app = Application(root)

root.mainloop()

1 个答案:

答案 0 :(得分:2)

您必须定义Entry fields,并将它们分配给属性。然后,在calc方法中,在这些输入字段上调用get,并在继续计算之前将该条目转换为float。

from tkinter import *
import math

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.widget()


    def widget(self):
        self.ori = Label(self, text="Insira o número desejado: ")
        self.ori.grid(row = 1, column = 0, columnspan = 2, sticky =W)

        self.ori2 = Label(self, text="Insira a porcentagem desejada: ")
        self.ori2.grid(row=2, column=0, columnspan = 2, sticky =W)

        self.num = Entry()
        self.num.grid(row=1, column=2, sticky=E)

        self.num1 = Entry()
        self.num1.grid(row = 2, column=2, sticky=E)

        self.label = Label(self, text="A porcentagem do número selecionado é: ")
        self.label.grid(row=3, column=0, columnspan=2, sticky=W)

        btstart = Button(self, text="Calcular", width=7, command=self.cal)
        btstart.grid(row=5, column=0)

        btstop = Button(self, text="Sair", width=7, command=self.close_window)
        btstop.grid(row=5, column=1)


    def cal(self):
        self.calc = float(self.num.get()) * float(self.num1.get()) / 100
        print(self.calc)


    def close_window(self):
        root.destroy()



root = Tk()

root.title("Programa de calculo")

app = Application(root)

root.mainloop()