Using Radio Button Widget In Python GUI Application


In this blog, I am going to create a Radio button widget in the Python GUI application. When a user selects the color in the radio button, the action will display the radio button color in the application screen.
Software requirement
  • Python 3.5 and IDLE (Python 3.5)
Programming code
  1. #Python Radiobutton using Application    
  2. import tkinter as tk    
  3. from tkinter import ttk    
  4. win = tk.Tk()    
  5. win.title("Python GUI App")    
  6. #Label Creation    
  7. ttk.Label(win, text="Choose the color:").grid(column=0,row=0)    
  8. #Colors    
  9. Color1='Red'    
  10. Color2='Blue'    
  11. Color3='Yellow'    
  12. #Action    
  13. def radioCall():    
  14.    radioSel=radioVar.get()    
  15.    if radioSel== 1:   
  16.       win.configure(background=Color1)   
  17.    elif radioSel== 2:  
  18.       win.configure(background=Color2)    
  19.    elif radioSel== 3:  
  20.       win.configure(background=Color3)  :  
  21. #Create three Radio Button    
  22. radioVar= tk.IntVar()    
  23. radio1=tk.Radiobutton(win, text=Color1, variable=radioVar, value=1, command=radioCall)    
  24. radio1.grid(column=1,row=1, sticky=tk.W, columnspan=3)    
  25. radio2=tk.Radiobutton(win, text=Color2, variable=radioVar, value=2, command=radioCall)    
  26. radio2.grid(column=1,row=2, sticky=tk.W, columnspan=3)    
  27. radio3=tk.Radiobutton(win, text=Color3, variable=radioVar, value=3, command=radioCall)    
  28. radio3.grid(column=1,row=3, sticky=tk.W, columnspan=3)    
  29. #Calling Main()    
  30. win.mainloop()    
About the code
  • First, I am importing the tkinter module.
  • Next, I will assign a class and variables and give the application title.
  • Next, I will create color values and radio button action condition.
  • Next, I will create a radio button and define values in the code.
  • Finally, I have started the Windows event loop by calling the mainloop method then executed the code.