Radiobutton控件
Radiobutton(单选按钮):组件用于实现多选一的问题。Radiobutton 组件可以包含文本或图像,每一个按钮都可以与一个 Python 的函数或方法与之相关联,当按钮被按下时,对应的函数或方法将被自动执行。
Radiobutton 组件仅能显示单一字体的文本,但文本可以跨越多行。另外,还可以为其中的个别字符加上下划线(例如用于表示键盘快捷键)。默认情况下,tab 按键被用于在按钮间切换。
每一组Radiobutton 组件应该只与一个变量相关联,然后每一个按钮表示该变量的单一值。
何时使用 Radiobutton 组件?
Radiobutton 组件是用于实现多选一的问题,它几乎总是成组地被使用,其中所有成员共用相同的变量。
用法
Radiobutton 组件跟 Checkbutton 组件非常相似,为了实现其“单选”行为,确保一组中的所有按钮的variable 选项都使用同一个变量,并使用 value 选项来指定每个按钮代表什么值:
参数
Radiobutton(master=None, **options) (class)
master – 父组件
**options – 组件选项
下面详细列举了各个选项的具体含义和用法:
activebackground
activeforeground
anchor
background <==>bg
bitmap
borderwidth <==>db
command
compound
cursor
disabledforeground
font
foreground <==>fg
height
highlightbackground
highlightcolor
highlightthickness
image
indicatoron
justify
padx
pady
relief
selectcolor
selectimage
state
takefocus
text
textvariable
underline
value
variable
width
wraplength
常用方法:
deselect():-- 取消该按钮的选中状态。
flash():
– 刷新 Radiobutton 组件,该方法将重绘Radiobutton 组件若干次(在 ACTIVE 和NORMAL 状态间切换)。
– 该方法在调试的时候很有用,也可以使用此方法提醒用户激活了该按钮。
invoke():
– 调用 Radiobutton 中 command 选项指定的函数或方法,并返回函数的返回值。
– 如果 Radiobutton 的状态是 DISABLED(不可用)或没有指定 command 选项,则该方法无效。
select():-- 将 Radiobutton 组件设置为选中状态。
实战内容:
1.创建三个RadioButton,实现简单的选择按钮
from tkinter import *
window = Tk()
window.title("My Window")
window.geometry('200x180')
var = StringVar()
lb = Label(window, bg='yellow',width=20,
text='empty')
lb.pack()
def print_selection():
lb.config(text='You have selected ' + var.get())
# 创建RadioButton按钮
rb1 = Radiobutton(window, text='Option A',
variable= var, value='A', command=print_selection)
rb1.pack()
rb2 = Radiobutton(window, text='Option B',
variable= var, value='B', command=print_selection)
rb2.pack()
rb3 = Radiobutton(window, text='Option C',
variable= var, value='C', command=print_selection)
rb3.pack()
window.mainloop()
import tkinter as tk
window = tk.Tk()
window.title("Python GUI")
window.geometry('200x180')
# 定义几个颜色的全局变量
COLOR1 = "Blue"
COLOR2 = "Gold"
COLOR3 = "Red"
# 单选按钮回调函数,就是当单选按钮被点击会执行该函数
def radCall():
radSel = radVar.get()
if radSel == 1:
# 设置整个界面的背景颜色
window.configure(background=COLOR1)
elif radSel == 2:
window.configure(background=COLOR2)
elif radSel == 3:
window.configure(background=COLOR3)
# 通过tk.IntVar() 获取单选按钮value参数对应的值
radVar = tk.IntVar()
# 当该单选按钮被点击时,会触发参数command对应的函数
rad1 = tk.Radiobutton(window, text=COLOR1, variable=radVar,
value=1, command=radCall)
# 参数sticky对应的值参考复选框的解释
rad1.grid(column=0, row=5, sticky=tk.W)
rad2 = tk.Radiobutton(window, text=COLOR2, variable=radVar,
value=2, command=radCall)
rad2.grid(column=1, row=5, sticky=tk.W)
rad3 = tk.Radiobutton(window, text=COLOR3, variable=radVar,
value=3, command=radCall)
rad3.grid(column=2, row=5, sticky=tk.W)
window.mainloop()