Biopy
Biopy

Reputation: 167

Put file path in global variable from browse button with tkinter

I'm just starting to use tkinter and it is a little difficult to handle it. Check this sample :

#!/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()

I juste created a browse button which keep the file path in the variable "filename" in the function openfile(). How can i put the content of "filename" in a variable out of the function ?

For example I want to put it in the variable P and print it in a terminal

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

I also also want to put the file path in a widget Entry(), and as same as below, get the text in the Entry widget in another global variable.

If someone knows, it would be nice.

Upvotes: 4

Views: 4799

Answers (1)

j_4321
j_4321

Reputation: 16169

There are at least two different ways of doing it:

1) Bundle your whole app in a class like this:

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()

In this case, filename is an attribute of the App, so it is accessible from any function inside the class.

2) Use a global variable:

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()

Upvotes: 4

Related Questions