我使用tkinter 8.5在python 3.4中创建了一个简单的GUI。我使用cx_freeze从这个GUI构建一个exe。现在当我运行这个exe时,有时我注意到该程序仍然显示在'后台进程'在任务管理器中,即使我使用退出按钮或使用窗口中的关闭按钮终止它。
GUI的工作方式如下:从下拉列表中选择文件类型,使用命令按钮读取文件并将其另存为单独的文件。现在只有在使用GUI后关闭GUI时才会出现此问题。如果我只是打开GUI并使用退出按钮或关闭按钮关闭它,它就不会作为后台进程。
它的行为是否正常?如果没有,我该怎么做才能正确终止它?
GUI的简化代码如下。功能' fileselect'调用模块' dataselect'中的函数。如果需要,我会提供“数据集”的代码。模块也。
from dataselect import *
from openpyxl import Workbook
from tkinter import *
from tkinter import ttk, filedialog
root = Tk()
root.title("Select Data File")
# Actual File Selection based on Combobox Selection
def fileselect():
file_type = filetype.get()
if file_type == ".txt":
text = selecttxt()
textfile = filedialog.asksaveasfile(mode='w', defaultextension=".txt")
for line in text:
for number in line:
textfile.write(str(number)+" ")
textfile.write('\n')
elif file_type == ".xlsx":
excel = selectxlsx()
excelfile = filedialog.asksaveasfile(mode='w', defaultextension=".xlsx")
excelfilename = excelfile.name
excelbook = Workbook()
excelsheet = excelbook.active
rows = 0
for excel_row in excel:
cols = 0
for excel_cell in excel_row:
excelsheet.cell(row=rows, column=cols).value = excel[rows][cols]
cols += 1
rows += 1
excelbook.save(excelfilename)
def quit():
global root
root.destroy()
# Select the File Type to be opened (.txt or .xlsx for now)
ttk.Label(root, text="Please select the file type").grid(column=2, row=1)
filetype = StringVar()
sel_type = ttk.Combobox(root,values=('.txt','.xlsx'),textvariable=filetype)
sel_type.grid(column=2,row=2,sticky=E)
# Command Button for Opening File
cb_open = ttk.Button(root, text="Select File", command=fileselect)
cb_open.grid(column=2, row=3)
# Command Button for Quitting GUI
cb_quit = ttk.Button(root, text="Quit", command=quit)
cb_quit.grid(column=1, row=3)
root.mainloop()
答案 0 :(得分:1)
您需要更改两件事: 1)将sys.exit()添加到退出方法
def quit():
root.quit
root.destroy
sys.exit()
2)将协议添加到根目录
root.protocol("WM_DELETE_WINDOW", quit)
最后,不要忘记导入sys。