import tkinter as tk #以别名tk导入tkinter库from tkinter import messageboxroot=tk.Tk() #创建主窗口的实例winroot.title("Frame组件测试窗口") #设置窗口的标题root.geometry("400x200+600+200")#设置窗口的大小和位置root.resizable(True,False) #设置窗口可水平缩放,禁止垂直缩放def show_selection(): """显示当前选中的项目""" selected_indices = listbox.curselection() if selected_indices: # 获取选中项的文本 selected_text = listbox.get(selected_indices[0]) messagebox.showinfo("选中项", f"您选择了:{selected_text}") else: messagebox.showwarning("无选中", "请先选择一个项目")def add_item(): """向列表框末尾添加新项目""" new_item = entry.get() if new_item.strip(): listbox.insert(tk.END, new_item.strip()) entry.delete(0, tk.END) else: messagebox.showwarning("输入为空", "请输入要添加的项目内容")def delete_selected(): """删除选中的项目""" selected = listbox.curselection() if selected: listbox.delete(selected[0]) else: messagebox.showwarning("未选中", "请先选择要删除的项目")#创建列表框组件对象listbox=tk.Listbox(root,selectmode=tk.SINGLE,fg="green",bg="yellow",height=10,width=30,)listbox.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)#在列表框中插入选项for item in ["苹果","香蕉","橙子","葡萄","西瓜"]: listbox.insert(tk.END,item) #列表方法#添加项目的输入框和按钮tk.Label(root,text="新项目:").pack(pady=(10, 0))entry=tk.Entry(root,width=15)entry.pack(pady=5)btn_add=tk.Button(root,text="添加",command=add_item)btn_add.pack(pady=5)#显示选中项的按钮btn_show=tk.Button(root,text="显示选中项",command=show_selection)btn_show.pack(pady=5)#删除选中项的按钮btn_delete=tk.Button(root,text="删除选中项",command=delete_selected)btn_delete.pack(pady=5)#退出按钮btn_exit=tk.Button(root,text="退出",command=root.destroy)btn_exit.pack(pady=20)tk.mainloop() #进入事件处理循环,防止窗口闪退