Search code examples
pythontkinterdecimal-point

How to round a number to n decimal places?


I want, what I enter in the entry field should be automatic rounded to n decimal points.

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

Solution

  • You do not get the expected result because when you run a.set(round(self.entry, 2)) inside initialize() , the value of self.entry.get() is always 0 (the default value after creation)

    You rather need to attach a callback to a button widget on which, after pressing, the behavior you are looking for will be executed:

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