About Lesson
In this TKinter Tutorial we are going to learn about TKinter RadioButton, we can use RadioButton class in tkinter.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import tkinter as tk from tkinter import ttk COLOR1 = "Blue" COLOR2 = "Red" COLOR3 = "Gold" class Window(tk.Tk): def __init__(self): super(Window, self).__init__() self.title("GeeksCoders.com - RadioButton ") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_radio() def rad_event(self): radSelected = self.radValues.get() if radSelected == 1: self.configure(background = COLOR1) elif radSelected == 2: self.configure(background=COLOR2) elif radSelected == 3: self.configure(background=COLOR3) def create_radio(self): self.radValues = tk.IntVar() self.rad1 = ttk.Radiobutton(self, text = COLOR1, value = 1, variable = self.radValues, command = self.rad_event) self.rad1.grid(column = 0, row = 0, sticky = tk.W, columnspan = 3) self.rad2 = ttk.Radiobutton(self, text=COLOR2, value=2, variable=self.radValues,command = self.rad_event) self.rad2.grid(column=0, row=1, sticky=tk.W, columnspan=3) self.rad3 = ttk.Radiobutton(self, text=COLOR3, value=3, variable=self.radValues,command = self.rad_event) self.rad3.grid(column=0, row=2, sticky=tk.W, columnspan=3) window = Window() window.mainloop() |
In here we want to get the value from tkinter radiobutton.
1 |
radSelected = self.radValues.get() |
After that we are going to create our RadioButton, and we add the value for the radiobutton, also you can add the command for the radiobutton, and we have connected the command with rad_event() method. and at the end add the radiobutton in to grid layout.
1 2 |
self.rad1 = ttk.Radiobutton(self, text = COLOR1, value = 1, variable = self.radValues, command = self.rad_event) |
And this is our method, we have connected this method with command of radiobutton, basically in this method we want to change our window color based on user selection.
1 2 3 4 5 6 7 8 9 10 11 |
def rad_event(self): radSelected = self.radValues.get() if radSelected == 1: self.configure(background = COLOR1) elif radSelected == 2: self.configure(background=COLOR2) elif radSelected == 3: self.configure(background=COLOR3) |
Run the complete code and this will be the result.