用于停止Tkinter的Python脚本(Python script to stop Tkinter)

我有以下代码使用Tkinter的askopenfilename来启用用户选择文件。 然后将该文件的内容用于图形。 我只使用Tkinter来允许用户选择文件,没有别的。 因此,是否有Python脚本在文件打开后结束Tkinter,我希望它位于标有“##”的行中。 因为Tkinter仍在运行,当它不需要时。 我的代码所针对的代码程序是在绘制图形时停止的。 这是我的代码:

Exampe of the data x,y, 1,4, 3,9, 6,7, ,, #Code starts import numpy as np from Tkinter import Tk from tkFileDialog import askopenfilename import matplotlib.pyplot as plt Tk().withdraw() # keep the root window from appearing (dont want full Gui) filename = askopenfilename()# show an "Open" dialog box and return the path to the selected file print(filename) data = np.genfromtxt(filename, dtype=[('x',float),('y',float)],comments='"', delimiter=',',skip_header=1,missing_values=True) ##Location of tkinter stop code## x=data['x'] x = x[np.logical_not(np.isnan(x))] #Remove Nan values y=data['y'] y = y[np.logical_not(np.isnan(y))] # Remove Nan values plt.plot(x, y, 'ko', ms=4) plt.show() #Code Ends

I have the following code that uses Tkinter's askopenfilename to enable the user to select a file. The contents of this file is then used for a graph. I'm only using Tkinter to allow the user to select the file, nothing else. Therefore is there Python script that will end Tkinter after the file has been opened, which I want to be located in the line marked with '##'. Because Tkinter is still running, when it doesn't need to be. The code program that my code is for is to stop when the graph is plotted. Here is my code:

Exampe of the data x,y, 1,4, 3,9, 6,7, ,, #Code starts import numpy as np from Tkinter import Tk from tkFileDialog import askopenfilename import matplotlib.pyplot as plt Tk().withdraw() # keep the root window from appearing (dont want full Gui) filename = askopenfilename()# show an "Open" dialog box and return the path to the selected file print(filename) data = np.genfromtxt(filename, dtype=[('x',float),('y',float)],comments='"', delimiter=',',skip_header=1,missing_values=True) ##Location of tkinter stop code## x=data['x'] x = x[np.logical_not(np.isnan(x))] #Remove Nan values y=data['y'] y = y[np.logical_not(np.isnan(y))] # Remove Nan values plt.plot(x, y, 'ko', ms=4) plt.show() #Code Ends

最满意答案

保持对Tk对象的引用,并在完成后调用其destroy方法:

tk = Tk() tk.withdraw() #do file dialog stuff (...) tk.destroy()

Keep a reference to your Tk object, and call its destroy method after you are done:

tk = Tk() tk.withdraw() #do file dialog stuff (...) tk.destroy()

更多推荐