Search code examples
pythontkinter

How to always center labels on top of one another


In my code, there are checkboxes to allow the data printed to be selected. But if I use .place and uncheck certain boxes, there will be a gap between the displays. E.g: labels with gaps

But, if i use pack(), the code will be stuck on top of the window. E.g: labels on top of screen

What should i do to make them always on top of each other, while also being centered.


Solution

  • from tkinter import *
    
    #functions
    
    def get_distance_travelled():
        # your code to find the distance travelled. I have given a dummy value
        return 15 #Remove this line and change according to yours
        
    def get_max_height():
        #your code to find max_height. I have given a dummy value
        return 100 #Remove this line and change according to yours
    
    def get_final_velocity():
        # your code to get final velocity. I have given a dummy value
        return 1000 #Remove this line and change according to yours
        
    def get_flight_time():
        # your code to get flight_time.I have given a dummy value
        return '10:10' #Remove this line and change according to yours
        
    def show_items():
        pop = Toplevel(root)
        pop.geometry('300x200')
        fn_lst = [get_distance_travelled(), get_max_height(), get_final_velocity(), get_flight_time() ]
        for i in range(len(ls)):
            if vardct[i].get()==1:
                
                # Remove the word 'Display ' from Display texts
                txt = keydct[i].replace('Display ', '')
                Label(pop, text=f'{txt} : {fn_lst[i]}').pack()
    
    #design
    
    root = Tk()
    root.geometry('300x200')
    
    
    # list containing display texts
    ls =    ['Display Distance Travelled', 
             'Display Max Height',
            'Display Final Velocity',
            'Display Flight Name']
            
            
    # Create 3 dicts say for display texts, intvars, and wdgts
    keydct, vardct, wdgdct = {}, {}, {}
    
    #create widgets and pack
    for i in range(len(ls)):
        keydct[i] = ls[i]
        vardct[i] = IntVar()
        wdgdct[i] = Checkbutton(root, text = keydct[i], variable = vardct[i])
        wdgdct[i].pack() 
    
    
        
         
        
    btn = Button(root, text = 'Show', command=show_items)
    btn.pack()
    root.mainloop()