Using Radio Button Widget In Python GUI Application

Intro

In this blog, I am going to create a Radio button widget in Python GUI application. When 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: win.configure(background=Color1)  
  16. elif radioSel== 2:win.configure(background=Color2)  
  17. elif radioSel== 3:win.configure(background=Color3)  
  18. #Create three Radio Button  
  19. radioVar= tk.IntVar()  
  20. radio1=tk.Radiobutton(win, text=Color1, variable=radioVar, value=1, command=radioCall)  
  21. radio1.grid(column=1,row=1, sticky=tk.W, columnspan=3)  
  22. radio2=tk.Radiobutton(win, text=Color2, variable=radioVar, value=2, command=radioCall)  
  23. radio2.grid(column=1,row=2, sticky=tk.W, columnspan=3)  
  24. radio3=tk.Radiobutton(win, text=Color3, variable=radioVar, value=3, command=radioCall)  
  25. radio3.grid(column=1,row=3, sticky=tk.W, columnspan=3)  
  26. #Calling Main()  
  27. win.mainloop()  

 

About the code

  • First, I am importing the tkinter module.
  • Next, I will assign a class and variables and give application title.
  • Next, I will create colors values and radio button action condition.
  • Next, I will create 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.

Output

 
 
 
Ebook Download
View all
Learn
View all