将文件路径放在带有tkinter的浏览按钮的全局变量中

时间:2017-01-11 21:05:57

标签: python tkinter

我刚刚开始使用tkinter,处理它有点困难。查看此示例:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import Tkinter as tk
import tkFileDialog

def openfile():
    filename = tkFileDialog.askopenfilename(title="Open file")
    return filename

window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()

window.mainloop()

我juste创建了一个浏览按钮,它将文件路径保存在openfile()函数的变量“filename”中。如何将“filename”的内容放在函数中的变量中?

例如,我想将它放在变量P中并将其打印在终端

def openfile():
    filename = tkFileDialog.askopenfilename(title="Open file")
    return filename

window = tk.Tk()
tk.Button(window, text='Browse', command=openfile).pack()

window.mainloop()

P = "the file path in filename"
print P

我还想把文件路径放在一个小部件Entry()中,和下面一样,在另一个全局变量中获取Entry小部件中的文本。

如果有人知道,那就太好了。

1 个答案:

答案 0 :(得分:1)

至少有两种不同的方法:

1)将您的整个应用程序捆绑在这样的类中:

import Tkinter as tk
import tkFileDialog

class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self) # create window

        self.filename = "" # variable to store filename

        tk.Button(self, text='Browse', command=self.openfile).pack()
        tk.Button(self, text='Print filename', command=self.printfile).pack()

        self.spinbox = tk.Spinbox(self, from_=0, to=10)
        self.spinbox.pack(pady=10)
        tk.Button(self, text='Print spinbox value', command=self.printspinbox).pack()

        self.mainloop()

    def printspinbox(self):
        print(self.spinbox.get())

    def openfile(self):
        self.filename = tkFileDialog.askopenfilename(title="Open file")

    def printfile(self):
        print(self.filename)

if __name__ == '__main__':
    App()

在这种情况下,filenameApp的属性,因此可以从类中的任何函数访问它。

2)使用全局变量:

import Tkinter as tk
import tkFileDialog

def openfile():
    global filename
    filename = tkFileDialog.askopenfilename(title="Open file")

def printfile():
    print(filename)

def printspinbox():
    print(spinbox.get())

window = tk.Tk()

filename = "" # global variable

tk.Button(window, text='Browse', command=openfile).pack()
tk.Button(window, text='Print filename', command=printfile).pack()

spinbox = tk.Spinbox(window, from_=0, to=10)
spinbox.pack(pady=10)
tk.Button(window, text='Print spinbox value', command=printspinbox).pack()

window.mainloop()