python中的Listbox错误用法

问题是,选择完后界面没有结束,窗口没有关闭。这是因为你在on_select函数里调用了root1.destroy()来关闭窗口,但是 mainloop() 依然会保持运行状态,因此即使窗口关闭,程序的流程依然没有终止。

问题分析:

root1.mainloop() 使得 select_sheet 函数进入了事件循环,并且当用户在列表框中选择一个项时,on_select() 被触发并关闭窗口。虽然你调用了 root1.destroy() 关闭了窗口,但由于 mainloop() 依旧在等待事件,因此程序并没有完全退出。

解决方法:

  1. 提前退出 mainloop():要解决这个问题,你需要确保在窗口关闭后能够退出事件循环并返回选中的项。你可以使用root1.quit() 来结束 mainloop(),然后返回选中的项。

  2. 修改 on_select 函数:为了让程序正确结束,我们可以在窗口关闭后通过 root1.quit() 来退出事件循环,然后在 select_sheet 函数里返回 selected_item

  3. root1.quit()  # 退出 mainloop 这里用root.withdraw()不显示主窗口不行,destroy()关闭窗口也不行

    from tkinter import TclError, filedialog, messagebox, Tk, Label, Listbox, Button
    from openpyxl import load_workbook
    
    def QAC_Check():
        root = Tk()
        root.withdraw()
        excel_file_path = filedialog.askopenfilename(title='Select Write EXCEL file', filetypes=[('Excel Files', '*.xlsx')])
        if not excel_file_path:
            messagebox.showerror("Error", "No file selected for saving Excel file!")
            return
        wb = load_workbook(excel_file_path)
        print(excel_file_path)
        sheetnames = wb.sheetnames
        selected_sheet = select_sheet(sheetnames)
        print(selected_sheet)
    
    def select_sheet(sheetnames):
        selected_item = None
        # 创建 GUI
        root1 = Tk()
        root1.geometry("300x300")  # 设置窗口大小
        lbl = Label(root1, text="Select a Sheet...")
        lbl.pack(pady=10)
        
        # 创建 Listbox 并插入字符串数组的内容
        listbox = Listbox(root1)
        for item in sheetnames:
            listbox.insert('end', item)
        listbox.pack(pady=10)
    
        # 定义选择按钮的回调函数
        def on_select():
            nonlocal selected_item
            try:
                selected_item = listbox.get(listbox.curselection())
                root1.quit()  # 退出 mainloop 这里用root.withdraw()不显示主窗口不行,destroy()关闭窗口也不行
            except TclError:
                messagebox.showwarning("Warning", "Please select an item before clicking Select.")
    
        # 创建一个按钮,点击时调用 on_select 函数获取选中的项
        btn = Button(root1, text="Select", command=on_select)
        btn.pack(pady=10)
    
        root1.mainloop()  # 启动事件循环
        return selected_item  # 返回选中的 sheet
    
    def main():
        root = Tk()
        button_name = messagebox.askquestion("Select Test Report", "Select yes for QAC and No for Poly", icon='question')
        if button_name == 'yes':  # 如果选择 QAC
            QAC_Check()
        else:
            messagebox.showinfo("Canceled", "What are you doing...")
    
    if __name__ == "__main__":
        main()
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值