Python - GUI(TKinter),从其他函数获取变量而不运行整个函数agan

时间:2016-10-03 12:15:31

标签: python function variables tkinter

我确实遇到了问题,我无法解决问题。问题是,我有两个单独的按钮。在一个按钮中,我想加载一个选定的文件。而另一个我想做一些搜索。 但是,如果不再运行整个函数,我就无法将变量从一个函数变为另一个函数。这意味着,查找按钮现在没用了。

from __future__ import print_function
from Tkinter import *
from Tkinter import Tk
from tkFileDialog import askopenfilename


def openFile():
    Tk().withdraw()
    txtFile = askopenfilename(defaultextension=".txt", filetypes=(("something", "*.txt"),("All Files", "*.*") ))
    print(txtFile)
    return txtFile


def Function():
    txtFile = openFile()
    with open(txtFile) as fp, open(('c:/map/test.txt'), 'w') as fo:
        for line in fp:

            if ('Hello') in line:
                content = line.strip() + " Hello detected "
            else:
                content = line.strip()
            fo.write(content + "\n")


def presentGUI():
    root = Tk()
    root.title("simulation")

    # Buttons
    button1 = Button(root, text="Select .txt file", command=openFile)
    button2 = Button(root, text="Run !", width=28, command=Function)

    # grid
    button1.grid(row=1, column=1)
    button2.grid(row=3, columnspan=3)

    root.mainloop()

presentGUI()

1 个答案:

答案 0 :(得分:1)

两种方法

  1. 为txtFile使用全局变量
  2. 使用OO并将函数创建为类的一部分,以便它们可以共享变量。
  3. 我给了你一个选项2的例子。因为这是我喜欢的工作方法。

    如果您点击"运行!"并且没有点击"选择.txt文件"首先它会提示你选择一个文件。 您可以从“应用程序”中的任何方法访问self.txtFile变量。类。

    from __future__ import print_function
    from Tkinter import *
    from Tkinter import Tk
    from tkFileDialog import askopenfilename
    
    class Application(Frame):
        def __init__(self,parent,**kw):
            Frame.__init__(self,parent,**kw)
            self.txtFile = None
            self.presentGUI()
    
        def openFile(self):
            ##Tk().withdraw()
            self.txtFile = askopenfilename(defaultextension=".txt", filetypes=(("something", "*.txt"),("All Files", "*.*") ))
            print(self.txtFile)
    
        def Function(self):
            if self.txtFile == None:
                self.openFile()
            with open(self.txtFile) as fp, open(('c:/map/test.txt'), 'w') as fo:
                for line in fp:
    
                    if ('Hello') in line:
                        content = line.strip() + " Hello detected "
                    else:
                        content = line.strip()
                    fo.write(content + "\n")
    
    
        def presentGUI(self):      
            # Buttons
            self.button1 = Button(self, text="Select .txt file", command=self.openFile)
            self.button2 = Button(self, text="Run !", width=28, command=self.Function)
    
            # grid
            self.button1.grid(row=1, column=1)
            self.button2.grid(row=3, columnspan=3)
    
    if __name__ == '__main__':
        root = Tk()
        root.title("simulation")
        app = Application(root)
        app.grid()
        root.mainloop()