Tkinter 建立含图像的Radiobutton
也可以将选项文字用图像取代,它的用法和标签Label相同。
Tkinter 建立含图像的Radiobutton 示例1
使用apidemos-list-1.png、apidemos-list-2.png、apidemos-list-3.png三个图片当作Radiobutton,读者可以选择某一选项,然后上方窗口中将列出所选择的项目。
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() # 选项按钮绑定的变量
var.set(" ") # 默认全不选
# var.set("") # 默认全选
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()
输出:
如果要建立含有图像和文字的选项按钮,需要在Radiobutton方法内增加text参数设置文字,增加compound参数设置图像与文字的位置。
Tkinter 建立含图像的Radiobutton 示例2
建立一个含有图像和文字的选项按钮组,本程序会将图像显示在文字的右边。
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() # 选项按钮绑定的变量
var.set(" ") # 默认全不选
# var.set("") # 默认全选
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()
输出: