2017-09-23 345 views
1

我在計算百分比時遇到了一些此代碼的問題。它會在計算中顯示一條錯誤消息,但我不知道如何顯示結果。這是我的代碼:Python百分比計算器

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

您必須定義Entry fields,並將它們分配給一個屬性。然後,在calc方法中,在這些輸入字段上調用get,並在繼續計算之前將條目轉換爲浮點數。

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

對不起,延遲,我能夠解決它雖然。這是簡單的事情,感謝指出它! –