带按钮的TkInter条目的返回值

时间:2016-05-15 17:25:46

标签: python-3.x tkinter

Python新手,在这里。我注意到关于从TkInter函数返回值的主题有很多问题,但没有一个解决方案似乎解决了我的问题。

我可以在print内成功self.e1path getPath.submit到shell,但我不能return到我的其余代码。我在课堂外使用print语句来测试我是否已成功返回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)

1 个答案:

答案 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)