首页 > 其他分享 >Tkinter 列表控件Listbox使用

Tkinter 列表控件Listbox使用

时间:2023-08-27 17:32:35浏览次数:41  
标签:lang 控件 Tkinter root items lb array Listbox select

1、使用StringVar初始化数据

from tkinter import *
import gjutil

# 初始化窗口
root = Tk()
root.title('listbox demo')
root.geometry(gjutil.getGeometry(root))

# 初始化数据
array_lang_data = ['python', 'golang', 'kotlin', 'dart', 'rust']
sv_lang_list = StringVar()
sv_lang_list.set(tuple(array_lang_data))

# 初始化控件
lb_lang = Listbox(root, listvariable=sv_lang_list)
lb_lang.pack()

root.mainloop()

显示效果如下

image-20230827153727619.png

2、获取列表选择数据

通过 ListBox 的 curselection() 方法获取当前选中项角标,再通过 ListBox 获取数据源获取对应数据。

# 获取选中数据
def get_select_item():
    try:
        item = lb_lang.get(lb_lang.curselection())
        label_select_display.config(text=item)
    except:
        mb.showerror(message="未选中任何选项")

label_select_display = Label(root)
btn_get_select = Button(root, text='获取数据', command=get_select_item)
        
label_select_display.pack()
btn_get_select.pack()

显示效果如下:

image-20230827154755467.png

3、设置为多选,并获取选中项

为 ListBox 设置属性 selectmode=MULTIPLE 即可支持多选。

当 ListBox 是多选时,其 curselection() 方法获取到的是当前选中项角标元组。

select_items = []  
def get_multi_select_items():
    array_select_indexs = lb_lang.curselection()
    if len(array_select_indexs) == 0:
        mb.showerror(message='未选中任何选项')
        return
    select_items.clear()
    for index in array_select_indexs:
        select_items.insert(len(select_items), lb_lang.get(index))
    label_select_display.config(text=' | '.join(select_items))

显示效果如下:

image-20230827155912873.png

4、向列表中追加数据

通过 ListBox 的 insert 方法插入数据:

btn_insert_data = Button(root, text='添加数据', command=lambda lb=lb_lang:lb.insert('end', "item"))

修改数据源 StringVar 中的数据:

def add_data():
		# 向数组中追加多条数据
    array_lang_data.extend(('Java', 'C', 'C++'))
    # 刷新 ListBox 数据源
    sv_lang_list.set(tuple(array_lang_data))

5、删除列表中数据

通过 ListBox 的 delete 方法删除指定角标数据:

def delete_items():
    array_select_indexs = lb_lang.curselection()
    print(type(array_select_indexs))
    if len(array_select_indexs) == 0:
        mb.showerror(message='未选中任何选项')
        return
    for index in reversed(array_select_indexs):
        lb_lang.delete(index)

也可以通过删除数据源中数据进行刷新,这里不再赘述。

6、附:全部代码

from tkinter import *
from tkinter import messagebox as mb
import gjutil

# 初始化窗口
root = Tk()
root.title('listbox demo')
root.geometry(gjutil.getGeometry(root))

# 初始化数据
array_lang_data = ['python', 'golang', 'kotlin', 'dart', 'rust']
sv_lang_list = StringVar()
sv_lang_list.set(tuple(array_lang_data))

# 初始化控件
lb_lang = Listbox(root, listvariable=sv_lang_list, selectmode=MULTIPLE, height=5)

# 获取单选选中数据
def get_select_item():
    try:
        item = lb_lang.get(lb_lang.curselection())
        label_select_display.config(text=item)
    except:
        mb.showerror(message="未选中任何选项")

# 存储所有选中数据
select_items = []
# 获取多选选中数据
def get_multi_select_items():
    array_select_indexs = lb_lang.curselection()
    print(type(array_select_indexs))
    if len(array_select_indexs) == 0:
        mb.showerror(message='未选中任何选项')
        return
    select_items.clear()
    for index in array_select_indexs:
        select_items.insert(len(select_items), lb_lang.get(index))
    label_select_display.config(text=' | '.join(select_items))
    
def add_data():
    # 向数组中追加多条数据
    array_lang_data.extend(('Java', 'C', 'C++'))
    # 刷新 ListBox 数据源
    sv_lang_list.set(tuple(array_lang_data))
    
def delete_items():
    array_select_indexs = lb_lang.curselection()
    print(type(array_select_indexs))
    if len(array_select_indexs) == 0:
        mb.showerror(message='未选中任何选项')
        return
    for index in reversed(array_select_indexs):
        lb_lang.delete(index)

label_select_display = Label(root)
btn_get_select = Button(root, text='获取数据', command=get_multi_select_items)
btn_insert_data = Button(root, text='添加数据', command=lambda lb=lb_lang:lb.insert('end', "item"))
btn_insert_data2 = Button(root, text='添加数据2', command=add_data)
btn_delete_data = Button(root, text='删除选中项', command=delete_items)

lb_lang.pack()       
label_select_display.pack()
btn_get_select.pack()
btn_insert_data.pack()
btn_insert_data2.pack()
btn_delete_data.pack()

root.mainloop()

标签:lang,控件,Tkinter,root,items,lb,array,Listbox,select
From: https://blog.51cto.com/u_16216552/7253830

相关文章

  • MFC-GetDlgItemText获取指定控件的文本
     TCHARname[256];HWNDhWnd=GetSafeHwnd();intn=::GetDlgItemText(hWnd,IDC_STATIC1,name,254);/*参数1:窗口句柄参数2:控件ID参数3:LPTSTRlpStr,//保存获取的文本的缓冲区参数4:nMaxCount指定了要拷贝到lpStr的字符串的最大......
  • tkinter文件管理
    以下是一个简单的tkinter实现文件管理的示例代码: ```pythonimporttkinterastkfromtkinterimportfiledialogimportos classFileManager:  def__init__(self,master):    self.master=master    self.master.title("文件管理器")  ......
  • tkinter窗口切换
    以下是使用tkinter实现窗口的创建、销毁和双向切换的示例代码: ```pythonimporttkinterastk classApp:  def__init__(self,root):    self.root=root    self.root.title("Tkinter窗口")    self.root.geometry("300x200")  ......
  • listbox组件
    Tkinter的Listbox是一个用于显示列表数据的组件,用户可以从中选择一个或多个项目。 以下是一些常用的Listbox方法及其说明: -pack():将Listbox放置在其父窗口中,并自动调整其大小以适应内容。-grid():将Listbox放置在其父窗口中的网格中,可以指定行和列的位置。-place():将Lis......
  • windows 桌面GUI自动化- 18.pywinauto 保存控件菜单树结构print_control_identifiers(
    前言.pywinauto可以使用print_control_identifiers()方法打印控件菜单树结构,这对我们查找控件非常方便。print_control_identifiers()查看相关源码defprint_control_identifiers(self,depth=None,filename=None):"""Printsthe'identifiers'......
  • WPF中窗口控件的跨线程调用
    在多线程里面,UI是不能直接跨线程使用的。在WinForm中,我们要跨线程访问窗口控件,只需要设置属性CheckForIllegalCrossThreadCalls=false;即可。在WPF中要设置Dispatcher属性。msg为要输出的内容privatedelegatevoidoutputDelegate(stringmsg);privatev......
  • WPF PasswordBox控件的使用
    在做登陆框的时候使用到PasswordBox,PasswordBox并不能像TextBox一样通过Binding就可以实现MVVM,需要用到依赖属性。 LoginView文件的代码:<StackPanelGrid.Row="0"Orientation="Horizontal"Margin="5"><TextBlockText="Username:"Width=&qu......
  • 遍历Tree控件中的节点
    classSapGuiTree:classTreeType(enum.Enum):SIMPLE=0LIST=1COLUMN=2@classmethoddefshow(cls,tree,node,indention):print(indention,node,[tree.GetItemText(node,col......
  • windows 桌面GUI自动化- 14.pywinauto 找到多个相同控件使用found_index
    前言pywinauto在查找到多个相同控件时操作会报错,可以使用found_index选择其中的一个查找到多个查找control_type="MenuBar"的所有控件frompywinautoimportApplicationapp=Application('uia').start("notepad.exe")win=app.window(title_re="无标题-记事本")#......
  • LinkButton控件,点击按钮带参数到后台
    LinkButton实现带参数到后台方法详解一:LinkButton控件常用的属性Text:用于设置控件显示的文本内容。ToolTip:鼠标悬停在控件上时显示的提示信息。CommandArgument:用于向服务器端的事件处理程序传递额外的参数。CommandName:用于标识LinkButton的命令名称,用于区分不同的......