Maybe this is easy, but I just don't figure it out ...
In the code below the "File Open" Button saves the filename to "name" -- but how can I access this variable outside of Tkinter? A return statement in "callback", but how would I access that since callback is inside the "Button" command?
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
name= askopenfilename()
print name
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
#HOW DO I ACCESS FILENAME AFTER MAINLOOP?
name = ????
eh, How about this?
from Tkinter import *
from tkFileDialog import askopenfilename
value_list = []
def callback():
name = askopenfilename()
value_list.append(name)
print name
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
# value_list[0] is filename
Related
This is my current code.
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
def main():
path = open_file()
print(path)
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
if file:
filepath = os.path.abspath(file.name)
quit()
print(filepath)
def quit():
win.destroy()
# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)
# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()
if __name__ == '__main__':
main()
I want to create a simple GUI to select a file and then use its path in other functions later on. In the current code the filepath prints out fine after the window closes in the open_file function, but it only works if the print statement is in the function. If I remove it from there and want to print it out(just to test) or use it further to pass it to other functions from main it doesn't seem to work. There is no error but it doesn't print anything either. Any idea?
The problem appears to be is wanting to return a value from a function called with a button. This is apparently not possible. The easiest solution I've found (without changing too much of your code structure) is to use a global variable for filepath. Now you can use it pretty much anywhere you want.
Also, I've removed path = open_file() from your main() function as it is redundant. The function is now called only when the button is pressed and not at every start of the program.
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
def main():
print(filepath)
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
if file:
global filepath
filepath = os.path.abspath(file.name)
quit()
def quit():
win.destroy()
# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10)
# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()
if __name__ == '__main__':
main()
I've been trying to get the printed output into a variable. Whenever I call the function it just simply repeats the button process. I tried to utilize global, but it doesn't seem to work.
Help pls thanks.
from tkinter import *
from tkinter import filedialog
import tkinter as tk
def openFile():
filepath = filedialog.askopenfilename(title="Open for me")
print(filepath)
window.destroy()
window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()
print , outputs the string to stdout it does not store the value in a variable, you'll need to store it yourself.
Since you're using a callback you can't return the value. The best way to implement this is to use classes, the bad way is to use a global variable to store the result
I'm assuming you are not familiar with classes, so a possible solution would be
from tkinter import *
from tkinter import filedialog
import tkinter as tk
path = ""
def openFile():
global path
path = filedialog.askopenfilename(title="Open for me")
window.destroy()
window = tk.Tk()
window.title("Insert Excel File")
window.geometry("200x200")
button = Button(text="Open",command=openFile,height=3,width=10)
button.pack()
window.mainloop()
# do something with path e.g. print
print(path)
im trying to make only the file name show up using filedialog
here's the example :
import tkinter as tk
import pygame
from tkinter import filedialog
root = tk.Tk()
controls_frame = tk.Frame(root)
controls_frame.pack()
def add_name():
name = filedialog.askopenfile()
names.insert(filedialog.END,name)
names = tk.Listbox(root,bg="black",fg="red",width=60,height=6)
names.pack(pady=0,side='bottom')
add_name_btn = tk.Button(controls_frame , text='add name' , command=add_name)
add_name_btn.grid(column=3,row=0,padx=20)
root.mainloop()
it shows the full directory to the file, which i dont want.
how do i remove the directory that it shows on box?
The module os can help with this:
import os
def add_name():
name = os.path.basename(str(filedialog.askopenfile()))
name = name.replace("' mode='r' encoding='UTF-8'>", "")
names.insert(filedialog.END,name)
You can do it like this.
I found this solution on another post.
import tkinter
from tkinter import filedialog
def filename123():
global filename1, nopath1
filename1 = filedialog.askopenfilename()
nopath1 = filename1.split("/")[len(filename1.split("/"))-1]
filename123()
Using Python Tkinter I am trying to get the directory path of selected Folder. I do not want to load a file or navigate to a file but get the folder path like
How can I do this?
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Update
from Tkinter import *
from tkFileDialog import askopenfilename
from tkinter import filedialog #for Python 3
def callback():
name= askopenfilename()
directory = filedialog.askdirectory()
print directory
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
You can use askdirectory from filedialog as follows:
from tkinter import filedialog #for Python 3
directory = filedialog.askdirectory()
Ok Looks like I find the solution on my own. Putting here which might help someone else in future.
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
print(dirname)
I'm making a program that you use the askopenname file dialog to select a file, which I then want to save the directory to a string so I can use another function (which I already made) to extract the file to a different location that is predetermined.
My button code that opens the file dialog is this:
`a = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))`
This should be what you want:
import tkinter
import tkinter.filedialog
import getpass
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
# Get the file
file = tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)
# Split the filepath to get the directory
directory = os.path.split(file)[0]
print(directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()
If you know where the file actually is, you could always just ask for a directory instead of the file using:
from tkFileDialog import askdirectory
directory= askdirectory()
Then in the code:
import tkinter
import tkinter.filedialog
import getpass
from tkFileDialog import askdirectory
# Need this for the `os.path.split` function
import os
gui = tkinter.Tk()
user = getpass.getuser()
def click():
directory= askdirectory()
print (directory)
button = tkinter.Button(gui, command=click)
button.grid()
gui.mainloop()