In this article, we shall see how to change or switch between Multiple Background colors in Tkinter.
Radiobutton:
Radiobutton is a widget that lets us choose an option from multiple options. Tkinter provides Radiobutton using which we can display multiple options in our GUI application.
Syntax:
tk.Radiobutton(text=some_name,value=give_name_that_of_text,variable=Tkinter_Variable)
for option in [“Brown”,”Black”,”Orange”,”Green”,”Red”]:
rd = tk.Radiobutton(root,text=”%s” %option,value=option,variable=choice)
rd.pack()
In order to display a Variable for each Radiobutton, we shall initialize Tkinter String Variable. Using String Variable we can perform the set and get method. Initially using String Variable we shall initialize Purple as the default color.
Syntax:
var = tk.StringVar()
choice = tk.StringVar(root,"purple") # initialize # after button click: color = choice.get()
Canvas:
A Tkinter canvas can be used to draw in a window, create images and add color.
canva = tk.Canvas(root,bg="purple") canva.place(x=-1,y=-1,width=300,height=300)
The place() method is a layout manager that is used to place a widget within the GUI window.
Button:
The button is used to trigger events in the GUI applications. You can add a command as the argument which calls the function to be executed on a button click. In simple words, Button is used to toggle events.
btn = tk.Button(text=”Change BG”,command=trigger_some_change,bd=4)
btn.pack()
bd argument means border. And the pack is also a layout manager that is used to display the widget on GUI following in specific order.
Example:
Python3
import tkinter as tk # configure window and its dimension # make window fixed root = tk.Tk() root.geometry( "300x300" ) root.resizable( False , False ) def change(): # change color after button triggers color = choice.get() # tkinter variable get method canva.configure(bg = color) choice = tk.StringVar(root, "purple" ) # create canva to play with background colors canva = tk.Canvas(root, bg = "purple" ) canva.place(x = - 1 , y = - 1 , width = 300 , height = 300 ) # create 5 Radio Buttons for option in [ "Brown" , "Black" , "Orange" , "Green" , "Red" ]: tk.Radiobutton(root, text = "%s" % option, value = option, variable = choice, padx = 10 , pady = 5 ).pack() # button to trigger colour change tk.Button(text = "Change BG" , command = change, bd = 4 ).place(x = 100 , y = 180 ) root.mainloop() |
Output: