问题是,选择完后界面没有结束,窗口没有关闭。这是因为你在on_select
函数里调用了root1.destroy()
来关闭窗口,但是 mainloop()
依然会保持运行状态,因此即使窗口关闭,程序的流程依然没有终止。
问题分析:
root1.mainloop()
使得 select_sheet
函数进入了事件循环,并且当用户在列表框中选择一个项时,on_select()
被触发并关闭窗口。虽然你调用了 root1.destroy()
关闭了窗口,但由于 mainloop()
依旧在等待事件,因此程序并没有完全退出。
解决方法:
-
提前退出
mainloop()
:要解决这个问题,你需要确保在窗口关闭后能够退出事件循环并返回选中的项。你可以使用root1.quit()
来结束mainloop()
,然后返回选中的项。 -
修改
on_select
函数:为了让程序正确结束,我们可以在窗口关闭后通过root1.quit()
来退出事件循环,然后在select_sheet
函数里返回selected_item
-
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()