Home > Software design >  Align radio buttons horizontally in python using tkinter
Align radio buttons horizontally in python using tkinter

Time:07-30

I have to program this application for one of my CS classes and I'm stumped attached is the code the radio buttons need to go horizontally when I use the .grid() it gives me the error the slaves are already managed by .pack() so I can't use .grid()

        self.label_name = Label(self.frame_name, text='Age')
        self.entry_name = Entry(self.frame_name)
        self.label_name.pack(padx=5, side='left')
        self.entry_name.pack(padx=15, side='left')
        self.frame_name.pack(anchor='w', pady=10)
        
        status_options = ["Student", "Staff", "Both"]
        x = IntVar()
        
        def clicked(self):
            print('helloworld')
            
        for index in range(len(status_options)):
            statusBar = Radiobutton(text=status_options[index],variable=x,value=index,padx=5).pack()
        buttonSave = Button(text="SAVE", command = clicked(self))
        buttonSave.pack(anchor='w', padx=75)

CodePudding user response:

Put the buttons in a frame and specify the side to pack each radio button as illustrated below.

import tkinter

class PersonalDetails(tkinter.Tk):
    def __init__(self):
        super(PersonalDetails, self).__init__()
        self.geometry("300x200 0 0")
        self.title("Personal Information")
        
        self.frame_name = tkinter.Frame(self)
        self.frame_name.pack(anchor='w', pady=10)
        
        self.label_name = tkinter.Label(self.frame_name, text='Age')
        self.label_name.pack(padx=5, side='left')
    
        self.entry_name = tkinter.Entry(self.frame_name)
        self.entry_name.pack(padx=15, side='left')
        
        # Radio buttons frame.
        self.buttons_frame = tkinter.Frame(self)
        self.buttons_frame.pack(fill=tkinter.BOTH)
        
        buttonSave = tkinter.Button(self,text="SAVE", command = self.clicked, padx=10)
        buttonSave.pack(anchor='w', padx=75, pady=10) 
        
        
        
        status_options = ["Student", "Staff", "Both"]
        x = tkinter.IntVar()
        for index in range(len(status_options)):
            tkinter.Radiobutton(self.buttons_frame,text=status_options[index],variable=x,value=index,padx=5).pack(side=tkinter.LEFT)
        
        
    def clicked(self):
        print('helloworld')
            
        
        
if __name__ == "__main__":
    details = PersonalDetails()
    details.mainloop()

Output:

enter image description here

  • Related