# Listbox窗口部件:
# 用户输入按钮添加,鼠标选择按钮删除
import tkinter as tk
# 创建主窗口对象,设置窗口大小位置
window = tk.Tk() # 创建主窗口对象
window.geometry('400x300+200+200')
window.title('My Window')
# 列表框
# selectmode鼠标模式默认单选browse,多选multiple,鼠标移动选测extended
listbox = tk.Listbox(window, selectmode='extended')
iterms = ['HTML5', 'CSS3', 'JavaScript', 'Python3', 'Jquery']
for i in iterms:
listbox.insert('end', i)
listbox.pack(side='left', expand=0, fill='y') # expand 组件可拉升,fill取Y方向填充
def add_item(): # 从输入框中添加选项
s = entry1.get()
if not s == '':
index = listbox.curselection() # 返回当前选中项的索引
if len(index):
listbox.insert(index[0], s) # 有选中项,在选中项前面添加
else:
listbox.insert('end', s) # 没有选中项,添加到最后
def remove_item(): # 从列表框中删除选项
index = listbox.curselection()
if len(index): # 有选中删除项
if len(index) > 1:
listbox.delete(index[0], index[-1]) # 选中多个删除项
else:
listbox.delete(index[0]) # 选中一个删除项
# 设置输入框
entry1 = tk.Entry(window, width=20)
entry1.pack(anchor='nw')
# 设置按钮
button1 = tk.Button(window, text='添加', command=add_item)
button2 = tk.Button(window, text='删除', command=remove_item)
button1.pack(anchor='nw')
button2.pack(anchor='nw')
window.mainloop() # 启动时间循环