Tkinter Radiobutton with Image
It is also possible to replace the option text with an image, which is used in the same way as the label Label.
Tkinter Radiobutton with Image Example#1
Using apidemos-list-1.png, apidemos-list-2.png and apidemos-list-3.png as Radiobutton, the reader can select a certain option and then the selected item will be listed in the upper window.
from tkinter import *
def printSelection():
label.config(text="You have chosen "+var.get()+".png.")
root = Tk()
root.title("apidemos.com")
img_chuckle = PhotoImage(file="apidemos-list-1.png")
img_shock = PhotoImage(file="apidemos-list-2.png")
img_snap = PhotoImage(file="apidemos-list-3.png")
var = StringVar() # Variables bound to option buttons
var.set(" ") # Default all unselected
# var.set("") # Default Select All
label = Label(root,text="This is a defult option, please choose...",bg="lightyellow",width=35)
label.pack()
rb_chuckle = Radiobutton(root,image=img_chuckle,
variable=var,value="chuckle",
command=printSelection)
rb_chuckle.pack()
rb_shock = Radiobutton(root,image=img_shock,
variable=var,value="shock",
command=printSelection)
rb_shock.pack()
rb_snap = Radiobutton(root,image=img_snap,
variable=var,value="snap",
command=printSelection)
rb_snap.pack()
root.mainloop()
Output:
If you want to create an option button containing image and text, you need to add text parameter inside Radiobutton method to set the text and add compound parameter to set the position of image and text.
Tkinter Radiobutton with Image Example#2
Create an option button group containing an image and text, and this program will display the image to the right of the text.
from tkinter import *
def printSelection():
label.config(text="You have chosen "+var.get()+".png.")
root = Tk()
root.title("apidemos.com")
img_chuckle = PhotoImage(file="apidemos-list-1.png")
img_shock = PhotoImage(file="apidemos-list-2.png")
img_snap = PhotoImage(file="apidemos-list-3.png")
var = StringVar() # Variables bound to option buttons
var.set(" ") # Default all unchecked
# var.set("") # Default Select All
label = Label(root,text="This is a defult option, please choose...",bg="lightyellow",width=35)
label.pack()
rb_chuckle = Radiobutton(root,image=img_chuckle,
text="Gakki chuckles.\t",compound=RIGHT,
variable=var,value="chuckle",
command=printSelection)
rb_chuckle.pack()
rb_shock = Radiobutton(root,image=img_shock,
text="Gakki shocks.\t",compound=RIGHT,
variable=var,value="shock",
command=printSelection)
rb_shock.pack()
rb_snap = Radiobutton(root,image=img_snap,
text="Gakki snaps her fingers.\t",compound=RIGHT,
variable=var,value="snap",
command=printSelection)
rb_snap.pack()
root.mainloop()
Output: