您的位置:首页技术文章
文章详情页

Python 窗体(tkinter)下拉列表框(Combobox)实例

【字号: 日期:2022-08-04 13:15:57浏览:2作者:猪猪

废话不多说,看代码吧!

import tkinterfrom tkinter import ttk def go(*args): #处理事件,*args表示可变参数 print(comboxlist.get()) #打印选中的值 win=tkinter.Tk() #构造窗体comvalue=tkinter.StringVar()#窗体自带的文本,新建一个值comboxlist=ttk.Combobox(win,textvariable=comvalue) #初始化comboxlist['values']=('1','2','3','4')comboxlist.current(0) #选择第一个comboxlist.bind('<<ComboboxSelected>>',go) #绑定事件,(下拉列表框被选中时,绑定go()函数)comboxlist.pack() win.mainloop() #进入消息循环

补充知识:Python GUI 之 Combobox 学习

1. 序言

本章介绍tkinter.ttk的Combobox控件。

2. 环境信息

********************************本系列运行平台:Windows10 64bitPython 版本:3.7********************************

3. Combobox

Combobox为下拉列表控件,它可以包含一个或多个文本项(text item),可以设置为单选或多选。使用方式为ttk.Combobox(root,option...)。

常用的参数列表如下:

参数

描述

master

代表了父窗口

height

设置显示高度、如果未设置此项,其大小以适应内容标签

width

设置显示宽度,如果未设置此项,其大小以适应内容标签

state

可读状态,如state= “readonly”

textvariable

设置textvariable属性

一些常用的函数:

函数

描述

get

返回制定索引的项值,如listbox.get(1);返回多个项值,返回元组,如listbox.get(0,2);返回当前选中项的索引listbox.curselection()

values

设定下拉列表的内容。如 data = ['a','b','c'], cbx['values'] = data

current(i)

指定下拉列表生成时显示在列表值,i = index。如current(2),显示列表中的第三个值

事件:

下拉列表没有command函数(方法)。

下拉列表的虚拟事件是 '<<ComboboxSelected>>'。

4. 实例

实例1

from tkinter import *from tkinter import ttk #Create an instancewin = Tk()win.title('Learn Combobox') #create a Labellb1 = Label(win, text = 'Below is a combobox 1', font = 'tahoma 12 normal')lb1.grid(column = 0, row = 0, padx = 8, pady = 4) def show_select_1():print('post_command: show_select')print(value.get()) #Define tkinter data typedata = ['a','b','c']value = StringVar() #Create a combobox, and tighter it to valuecbx_1 = ttk.Combobox(win, width = 12, height = 8, textvariable = value, postcommand = show_select_1)cbx_1.grid(column = 0, row = 1) #add data to comboboxcbx_1['values'] = data #======================================================================================================#create a Labellb2 = Label(win, text = 'Below is a combobox 2', font = 'tahoma 12 normal')lb2.grid(column = 0, row = 4, padx = 8, pady = 4) def show_data_2(*args):print('Event: ComboboxSelected')print(cbx_2.get()) #Define tkinter data typedata2 = ['a2','b2','c2','d2','e2'] #Create a combobox, and tighter it to valuecbx_2 = ttk.Combobox(win, width = 12, height = 8)cbx_2.grid(column = 0, row = 5) #set cbx_2 as readonlycbx_2.configure(state = 'readonly') #add data to comboboxcbx_2['values'] = data2#set the initial data [index =2] to shows up when win generatedcbx_2.current(2) #bind a eventcbx_2.bind('<<ComboboxSelected>>', show_data_2) win.mainloop()

以上这篇Python 窗体(tkinter)下拉列表框(Combobox)实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: