2016-05-15 182 views
0

Python新手,在這裏。我注意到關於從TkInter函數返回值的主題有很多問題,但沒有一個解決方案似乎解決了我的問題。從TkInter入口返回值與按鈕

我可以成功地將printself.e1pathgetPath.submit以內,但我不能return它到我的代碼的其餘部分。我在課堂外使用打印語句來測試我是否已成功返回CSV路徑。

from tkinter import * 
import tkinter as tk 
class getPath(tk.Tk): 
    def __init__(self): 
     tk.Tk.__init__(self) 
     self.label1 = tk.Label(self, text="CSV Path").grid(row=0, column=0) 
     self.e1 = tk.Entry(self, width=50) 
     self.e1Grid = self.e1.grid(row=0, column=1) 

     self.browse = tk.Button(self, text='Browse', command=self.getCSV).grid(row=0, column=2) 
     self.submit = tk.Button(self, text='Submit', command=self.submit).grid(row=1, column=1) 

    def getCSV(self): 
     self.fileName = filedialog.askopenfilename(filetypes = (('Comma Separated Values', '*.csv'), ('All Files', '*.*')), title = "Choose a CSV File") 
     self.e1.insert(10, self.fileName) 

    def submit(self): 
     self.e1Path = self.e1.get() 
     return self.e1Path 

app = getPath() 
app.mainloop() 
print(app) 
+0

我回答了您的問題嗎? –

回答

0

我想通了!我需要添加一個self.destroy()submit函數。這停止了​​主循環,讓我打電話self.e1path以外的功能使用app.e1path。新代碼:

from tkinter import * 
import tkinter as tk 
class getPath(tk.Tk): 
    def __init__(self): 
     tk.Tk.__init__(self) 
     self.label1 = tk.Label(self, text="CSV Path").grid(row=0, column=0) 
     self.e1 = tk.Entry(self, width=50) 
     self.e1Grid = self.e1.grid(row=0, column=1) 

     self.browse = tk.Button(self, text='Browse', command=self.getCSV).grid(row=0, column=2) 
     self.submit = tk.Button(self, text='Submit', command=self.submit).grid(row=1, column=1) 

    def getCSV(self): 
     self.fileName = filedialog.askopenfilename(filetypes = (('Comma Separated Values', '*.csv'), ('All Files', '*.*')), title = "Choose a CSV File") 
     self.e1.insert(10, self.fileName) 

    def submit(self): 
     self.e1Path = self.e1.get() 
     self.destroy() 

app = getPath() 
app.mainloop() 
print(app.e1Path)