2016-07-15 157 views
-1

我想要的是,我在输入字段中输入的内容应该自动舍入为n个小数点。如何在Python中将数字四舍五入到小数点后n位

import Tkinter as Tk 

root = Tk.Tk() 

class InterfaceApp(): 
    def __init__(self,parent): 
     self.parent = parent 
     root.title("P") 
     self.initialize() 


    def initialize(self): 
     frPic = Tk.Frame(bg='', colormap='new') 
     frPic.grid(row=0) 
     a= Tk.DoubleVar() 
     self.entry = Tk.Entry(frPic, textvariable=a) 
     a.set(round(self.entry.get(), 2)) 

     self.entry.grid(row=0) 
if __name__ == '__main__': 
    app = InterfaceApp(root) 
    root.mainloop() 
+0

是不是你的'一个'IntVar',例如整数...? –

+1

这是如何工作的?舍入何时发生?当你键入?当焦点离开?等等。 – mgilson

+0

它是'DoubleVar()',我修复了它。 –

回答

1

,因为当你运行a.set(round(self.entry, 2))initialize()你没有得到预期的结果,self.entry.get()值总是0(创建后的默认值)

你,而需要一个callback附加到一个按钮控件上,在按下后,您正在查找的行为将被执行:

import Tkinter as Tk 

root = Tk.Tk() 

class InterfaceApp(): 

    def __init__(self,parent): 
     self.parent = parent 
     root.title("P") 
     self.initialize() 

    def initialize(self): 
     frPic = Tk.Frame(bg='', colormap='new') 
     frPic.grid(row=0, column=0) 
     self.a = Tk.DoubleVar() 
     self.entry = Tk.Entry(frPic, textvariable=self.a) 
     self.entry.insert(Tk.INSERT,0) 
     self.entry.grid(row=0, column=0) 
     # Add a button widget with a callback 
     self.button = Tk.Button(frPic, text='Press', command=self.round_n_decimal) 
     self.button.grid(row=1, column=0) 
    # Callback  
    def round_n_decimal(self):  
     self.a.set(round(float(self.entry.get()), 2)) 

if __name__ == '__main__': 
    app = InterfaceApp(root) 
    root.mainloop() 
+0

我可以做到这一点没有按钮..也活着吗? –

+0

@MirzaGrbic你能解释一下你的意思吗?*一个实时按钮*? –

+0

当您输入一个值时,应该在您按下按钮之前自动舍入值。非常感谢Billal! –

0

我想你想要的不是舍入浮点值本身,而是想显示精度为n个小数点的浮点值。试试这个:

>>> n = 2 
>>> '{:.{}f}'.format(3.1415926535, n) 
'3.14' 
>>> n = 3 
>>> '{:.{}f}'.format(3.1415926535, n) 
'3.142' 

注:在你的代码试图把self.entry .I。即您尝试围绕Tk.Entry类型的实例。您应该使用为您提供字符串的self.entry.get()

如果你不熟悉这种字符串格式我使用外观here

+0

不,我想要圆形值本身(您在输入字段中输入的内容,它应该舍入)。我修好了,它仍然没有工作。 'a = Tk.DoubleVar()''self.entry = Tk.Entry(frPic,textvariable = a)''a.set(round(self.entry.get(),2))' –

+0

你是什么意思“它不工作”?请发布输出/结果 – Humbalan