Vivek
Vivek

Reputation: 89

tkinter Radiobutton: How to align multiline text with the button?

I am not able to find a way to align the radio button option to the first line of the multi line text.

For e.g in the attached image i want the option 1 and option 3 to align with there respective radio buttons.

Sample Code:

import tkinter as tk


root = tk.Tk()
var = tk.IntVar()
R1 = tk.Radiobutton(root, text="Option 1 with\n multline", variable=var, value=1)
R1.pack( anchor = 'w' )

R2 = tk.Radiobutton(root, text="Option 2", variable=var, value=2)
R2.pack( anchor = 'w' )

R3 = tk.Radiobutton(root, text="Option 3 with\n multine", variable=var, value=3)
R3.pack( anchor = 'w' )

R4 = tk.Radiobutton(root, text="Option 4", variable=var, value=4)
R4.pack( anchor = 'w' )


root.mainloop()

enter image description here

Upvotes: 2

Views: 603

Answers (1)

martineau
martineau

Reputation: 123491

As I said in a comment, I don't think the stock tkinter Radiobutton supports what you want to do. Fortunately it's not too difficult to craft a custom widget of your own that does.

Note that putting all the component widgets inside a Frame subclass makes the layout manager being used with it not affect the one that the user of the new class uses to position it (since normally one would want to avoid mixing them — see creating a custom widget in tkinter for more details).

import tkinter as tk


class MyRadioButton(tk.Frame):
    def __init__(self, parent, text, variable, value):
        tk.Frame.__init__(self, parent)

        self.rbtn = tk.Radiobutton(self, variable=variable, value=value)
        self.rbtn.grid(row=0, column=0, sticky="nw")

        self.label = tk.Label(self, text=text, anchor="w", justify="left")
        self.label.grid(row=0, column=1, sticky="nw")


if __name__ == '__main__':

    root = tk.Tk()
    var = tk.IntVar()
    R1 = MyRadioButton(root, text="Option 1 with\n multline", variable=var, value=1)
    R1.pack(anchor='w')

    R2 = MyRadioButton(root, text="Option 2", variable=var, value=2)
    R2.pack(anchor='w')

    R3 = MyRadioButton(root, text="Option 3 with\n multine", variable=var, value=3)
    R3.pack(anchor='w')

    R4 = MyRadioButton(root, text="Option 4", variable=var, value=4)
    R4.pack(anchor='w')

    root.mainloop()

Result:

screenshot showing custom radiobutton widget in action

Upvotes: 2

Related Questions