Tkinter (15) 单选按钮部件 Radiobutton

单选按钮部件的创建及其选项

每个部件都包含两部份, 指示器 indicator 及标签 label. 好几个这样的部件组成一群, 设置为同一个控制变量 (IntVar 或 StringVar)

import tkinter as tk
parent = tk.Tk()
radio_button = tk.Radiobutton(parent, option, ...)
选项 说明
activebackground active 时的背景色
activeforeground active 时的前景色
anchor 部件定位点,内定为 CENTER
bg or background 背景色,点阵图时则为颜色值 0 的颜色
bitmap 点阵图
bd or borderwidth 框的寛度, 内定为 2 点素
command 单选按钮部件状态改变时调用的程序
compound 图与文本共用时,图相对于文本的位置. LEFT/RIGHT/TOP/BOTTOM/CENTER, 内定为 None
cursor 当鼠标移到部件时,所显示的鼠标图示
disabledforeground disabled 时的前景色
font 文本字体
fg or foreground 前景色,点阵图时则为颜色值 1 的颜色
height 文本行数
highlightbackground 非聚焦时的聚焦颜色
highlightcolor 聚焦时的聚焦颜色
highlightthickness 聚焦厚度,内定 1, 0 则无
image 图片
indicatoron 是否显示指示器, 不显示时, 标签会变成一个按钮
justify 多行文本的对齐方式,LEFT/RIGHT/CENTER
offrelief 当 indicatoron=False, 标签按钮的花边样式, 内定为 RAISED
overrelief 当鼠标移到部件上方时, 所显示的花边样式
padx 水平间距,内定为 1 点素
pady 垂直间距,内定为 1 点素
relief 花边样式,内定为 FLAT
selectcolor 部件选定时的颜色, 内定为红色
selectimage 部件选定时的图片
state 部件状态, 内定为 NORMAL / ACTIVE / DISABLED
takefocus TAB 键在部件是否会循环焦点,1 则会,内定为空字符串,则仅在具有键绑定下循环焦点
text 文本字串,使用 \n 分行
textvariable 文本字串变量
underline 设置下底线的位置,内定 -1 为无
value 该单选按钮部件的选定值
variable 单选按钮部件群的选定变量
width 文本寛度,内定为显示文本或图片的尺寸
wraplength 文本分行寛度,单位为字数

单选按钮部件的方法

方法 说明
deselect() 不选择该部件
flash() 在 ACTIVE 的颜色和 NORMAL 颜色之间闪烁切换
invoke() 单击按钮,返回回调的返回值
select() 选择该部件

范例视窗及代码

Python

import tkinter as tk

def update(i):
    label.configure(text=f"You select '{texts[i]}' and value is {values[i]}")

root = tk.Tk()
root.wm_title("Radiobutton Demo")
font = ('Courier New', 20, 'bold')

texts = ['Cat', 'Dog', 'Pig']
values = [0, 1, 99]
select = tk.IntVar()
select.set(99)
widget = [None]*len(texts)
for i, (t, v) in enumerate(zip(texts, values)):
    widget[i] = tk.Radiobutton(
        text=t, value=v, font=font, variable=select,
        command=lambda index=i: update(index))
    widget[i].grid(row=0, column=i)

label = tk.Label(text='', width=40, font=font)
label.grid(row=1, column=0, columnspan=len(texts))

root.mainloop()
本作品采用《CC 协议》,转载必须注明作者和本文链接
Jason Yang
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!