Python Tkinter 之Listbox控件(Python GUI 系列12)

Python Tkinter 之Listbox控件(Python GUI 系列12)

1. 序言

    本章介绍Tkinter的Listbox控件,本文是Python GUI系列的第12篇文章,整个系统约20篇博客,将全面的介绍Python Tkinter常用控件,最后还将基于Tkinter搭建两个比较完整的小项目。

2. 环境信息

********************************
本系列运行平台:Mac OS 10.13.4
Python 版本:3.6.4

********************************   

3. Listbox

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

常用的参数列表如下:

参数

描述

master

代表了父窗口

bg

背景色,如bg=”red”, bg="#FF56EF"

fg

前景色,如fg=”red”, fg="#FF56EF"

height

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

relief

指定外观装饰边界附近的标签,默认是平的,可以设置的参数:flat、groove、raised、ridge、solid、sunken

width

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

state

设置组件状态;正常(normal),激活(active),禁用(disabled)

bd

设置Button的边框大小;bd(bordwidth)缺省为1或2个像素

selectmode

选择模式,MULTIPLE:多选 BROWSE:通过鼠标的移动选择 EXTENDED:shift和ctrl配合使用

listvariable

设置listvariable属性

一些常用的函数:

函数

描述

insert

追加item,如listbox.insert(0,"addBox1","addBox2")

delete

删除item,如listbox.delete(3,4),删除全部(0,END)

select_set

选中,如listbox.select_set(0,2)

select_clear

取消选中如listbox.select_clear(0,1)

get

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

curselection()

返回当前选中项的索引,如listbox.curselection()

selection_includes

判断当前选中的项目中是否包含某项,如listbox.selection_includes(4)


4. 实例

实例1

from tkinter import *


def show_msg(*args):
    indexs = listbox1.curselection()
    index = int(indexs[0])
    listbox2.see(index)
    listbox2.select_set(index)

myWindow = Tk()
myWindow.title("listbox练习")
#创建列表显示内容
names = ("梅长苏","誉王","飞流","夏冬","霓凰郡主","蒙挚","萧景睿","谢玉")
players = ("胡歌","黄维德","吴磊","张龄心","刘涛","陈龙","程皓枫","刘奕君")  # 刘奕君

list1 = StringVar(value=names)
list2 = StringVar(value=players)

#创建两个Listbox,分别设置为单选、多选类型
listbox1 = Listbox(myWindow,height=len(names),listvariable=list1,selectmode="browse")
listbox2 = Listbox(myWindow,height=len(players),listvariable=list2,selectmode="extended")

listbox1.grid(row=1,column=1,padx=(10,5),pady=10)
listbox2.grid(row=1,column=2,padx=(5,10),pady=10)

listbox1.select_set(4)
# listbox2.select_set(1,5)

#设置第二个表格的项目颜色等
for i in range(len(players)):
    listbox2.itemconfig(i,fg="blue")
    if not i%2:
        listbox2.itemconfig(i,bg="#f0f0ff")

#为第一个Listbox设置绑定事件
listbox1.bind("<<ListboxSelect>>",show_msg)

myWindow.mainloop()

运行结果:


猜你喜欢

转载自blog.csdn.net/jin_kwok/article/details/80147365