如何删除 Tkinter 列表框中的多个选定项目?
先决条件: Tkinter,Tkinter 中的列表框
Python为开发 GUI(图形用户界面)提供了多种选择。在所有 GUI 方法中,Tkinter 是最常用的方法。它是Python附带的 Tk GUI 工具包的标准Python接口。 Python with Tkinter 是创建 GUI 应用程序的最快、最简单的方法。
在本文中,我们将学习如何使用Python中的 Tkinter 在 Listbox 中删除多个选中的复选框。
让我们一步一步地理解实现:-
1. 创建普通的 Tkinter 窗口
Python3
from tkinter import *
root = Tk()
root.geometry("200x200")
root.mainloop()
Python3
# Import Module
from tkinter import *
# Create Object
root = Tk()
# Set Geometry
root.geometry("200x200")
# Add Listbox
listbox = Listbox(root, selectmode=MULTIPLE)
listbox.pack()
# Listbox Items List
items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
# Iterate Through Items list
for item in items:
listbox.insert(END, item)
Button(root, text="delete").pack()
# Execute Tkinter
root.mainloop()
Python3
# Import Module
from tkinter import *
# Function will remove selected Listbox items
def remove_item():
selected_checkboxs = listbox.curselection()
for selected_checkbox in selected_checkboxs[::-1]:
listbox.delete(selected_checkbox)
# Create Object
root = Tk()
# Set Geometry
root.geometry("200x200")
# Add Listbox
listbox = Listbox(root, selectmode=MULTIPLE)
listbox.pack()
# Listbox Items List
items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
# Iterate Through Items list
for item in items:
listbox.insert(END, item)
Button(root, text="delete", command=remove_item).pack()
# Execute Tkinter
root.mainloop()
输出:
2.使用Listbox()方法添加Listbox
句法:
Listbox(root, bg, fg, bd, height, width, font, ..)
蟒蛇3
# Import Module
from tkinter import *
# Create Object
root = Tk()
# Set Geometry
root.geometry("200x200")
# Add Listbox
listbox = Listbox(root, selectmode=MULTIPLE)
listbox.pack()
# Listbox Items List
items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
# Iterate Through Items list
for item in items:
listbox.insert(END, item)
Button(root, text="delete").pack()
# Execute Tkinter
root.mainloop()
输出:
3. 从列表框中删除所选项目
- 使用curselection()方法从列表框中获取选定项目的列表。
- 遍历所有列表并使用delete()方法删除项目
以下是实现:-
蟒蛇3
# Import Module
from tkinter import *
# Function will remove selected Listbox items
def remove_item():
selected_checkboxs = listbox.curselection()
for selected_checkbox in selected_checkboxs[::-1]:
listbox.delete(selected_checkbox)
# Create Object
root = Tk()
# Set Geometry
root.geometry("200x200")
# Add Listbox
listbox = Listbox(root, selectmode=MULTIPLE)
listbox.pack()
# Listbox Items List
items = ["Apple", "Orange", "Grapes", "Banana", "Mango"]
# Iterate Through Items list
for item in items:
listbox.insert(END, item)
Button(root, text="delete", command=remove_item).pack()
# Execute Tkinter
root.mainloop()
输出: