关于python-tkinter-ttk-Combobox详解

1、介绍

Combobox是在tkinter模块下的ttk模块的一个部件,产生的效果是一个下拉列表框,它是GUI当中的一个装饰(widget),当用户点击下拉列表获取值的时候是从列表当中选取的,那么就会产生一个名为<<ComboboxSelected>>的虚拟事件,也就是对应python官方手册里面的这句话:The combobox widgets generates a <<ComboboxSelected>> virtula event when the user selects an element from the list of values.


该部件有三个方法:current()、get()、set()

current(index) 设置下拉列表首选项,参数可填写值列表中对应的index
get() Returns the current value of the combobox.
set(value) Sets the value of the combobox to value.

有了这三个方法之后,基本的部件设置是可以满足的

2、具体细节演示

This widget is a combination of an Entry and a drop-down menu.
这个装饰是输入框和下拉列表的结合
In your application, you will see the usual text entry area, with a downward-pointing arrow.
在应用当中,可以看到常用的输入框区域和向下指向的箭头
在这里插入图片描述

When the user clicks on the arrow, a drop-down menu appears. If the user clicks on one, that choice replaces the current contents of the entry.
当用户点击向下的箭头时,下拉菜单会出现。如果用户点击了其中的某一项,被选中的内容会替代掉输入框当前的内容
在这里插入图片描述

However, the user may still type text directly into the entry (when it has focus), or edit the current text.
当然了用户也可以直接在输入框里进行编辑
在这里插入图片描述
如果说要创建一个下拉列表装饰,那么要遵循以下语法
在这里插入图片描述

cbox = ttk.Combobox(window, width = 26)

window是Combobox所对应的父容器,width是指以小部件字体的平均大小字符指定指示输入窗口的所需宽度的整数值

widthThis option specifies the width of the entry area as a number of characters. The actual width will be this number times the average width of a character in the effective font. The default value is 20.

在创建下拉列表菜单时要注意下面的参数

valuesThe choices that will appear in the drop-down menu, as a sequence of strings.
cbox['values'] = ['请选择内容', 'text1', 'text2', 'text3']

设置好这些之后进行一个放置即可

cbox.place(x = 0, y = 0)

此时,设置一个下拉首选项,成为输入框中默认显示的内容

cbox.current(0)

如果想要让窗口内容可以编辑,那么状态正常即可,或者设置成只读或禁用

state“正常”,“只读”或“禁用”之一。在“只读”状态下,该值可能不会被直接编辑,并且用户只能从下拉列表中选择其中一个值。在“正常”状态下,文本字段可直接编辑。在“禁用”状态下,不可能进行交互。
cbox['state'] = 'readonly'

如果想要实现交互触发,则可以调用bind函数进行绑定
语法规则是:bind(事件名称, 被触发的函数名)
在对应函数体当中使用get()方法进行值的获取即可

def showMsg(*args):
	print(cbox.get())
cbox.bind('<<ComboboxSelected>>', showMsg)
  • 13
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值