I want to create a tkinter window, where it will appear the files of a folder as a dropdown menu and a Select button, such that when I select an element from the previous list the full path will be saved into a new variable. Apparently, I need to give an appropriate command.
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command= ?)
w.pack()
root.mainloop()
I think what you need here is actually a binding. Button not required.
Here is an example that will list everything in your selected directory and then when you click on it in the Combo Box it will print out its selection.
Update, added directory and file name combining to get new full path:
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
new_full_path = ""
root = Tk()
# we use StringVar() to track the currently selected string in the combobox
current_selected_filepath = StringVar()
b = ttk.Combobox(master=root, values=current_selected_filepath)
function used to read the current StringVar of b
def update_file_path(event=None):
global b, new_full_path
# combining the directory path with the file name to get full path.
# keep in mind if you are going to be changing directories then
# you need to use one of FileDialogs methods to update your directory
new_full_path = "{}{}".format(indir, b.get())
print(new_full_path)
# here we set all the values of the combobox with names of the files in the dir of choice
b['values'] = os.listdir(indir)
# we now bind the Cobobox Select event to call our print function that reads to StringVar
b.bind("<<ComboboxSelected>>", update_file_path)
b.pack()
# we can also use a button to call the same function to print the StringVar
Button(root, text="Print selected", command=update_file_path).pack()
root.mainloop()
Try something like this:
w = Button(master=root, text='Select', command=do_something)
def do_something():
#do something
In the function do_something you create what you need to get the full path. You can also pass vars into the command.
get()
Returns the current value of the combobox.(https://docs.python.org/3.2/library/tkinter.ttk.html)
from Tkinter import *
import tkFileDialog
import ttk
import os
indir= '/Users/username/results'
#This function will be invoked with selected combobox value when click on the button
def func_(data_selected_from_combo):
full_path = "{}/{}".format(indir, data_selected_from_combo)
print full_path
# Use this full path to do further
root = Tk()
b = ttk.Combobox(master=root, values=os.listdir(indir)) # This will create a dropdown menu with all the elements in the indir folder.
b.pack()
w = Button(master=root, text='Select', command=lambda: func_(b.get()))
w.pack()
root.mainloop()
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'm new to python, and I'm trying to work with “tkinter”.
The bottom line is that I need to assign a folder deletion function to the button
my code looks like this
from tkinter.ttk import LabeledScale
import shutil
import pathlib
master = tk.Tk()
lable = tk.Label(text ="delete this?")
lable.pack()
path = "C:\\Users\\kolba\\Desktop\\pythonpool"
def buttonClick():
shutil.rmtree(path)
button = tk.Button(master, text ="yes!!!", ) #what to put after the comma?
button.pack()
master.mainloop()
how do I make the button work?
You are looking for command
Function or method to be called when the button is clicked.
In this case
def buttonClick():
shutil.rmtree(path)
button = tk.Button(master, text="yes!!!", command=buttonClick)
You should pass the function after the comma:
button = tk.Button(master, text ="yes!!!", command = buttonClick)
You can read more about tk.Button here
you could add a font and you should put a command otherwise that button will be for nothing. something like this:
from tkinter.ttk import LabeledScale
import shutil
import pathlib
master = tk.Tk()
lable = tk.Label(text ="delete this?")
lable.pack()
path = "C:\\Users\\kolba\\Desktop\\pythonpool"
def buttonClick():
shutil.rmtree(path)
button = tk.Button(master, text ="yes!!!",command=buttonClick )
button.pack()
master.mainloop()
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)
I am starting in tkinter and I have generated a list with the elements that are in a certain folder and I need to show them in the interface.
I put it in a label but it shows me the elements horizontally and I need it to show one below the other, is there a way to do this?
from tkinter import *
from os import listdir
raiz = Tk()
ruta = './imagenes'
fotos = Frame()
fotos.place(x=0,y=0)
fotos.config(bd=10,relief="groove",width="500", height="200")
fotografias = StringVar()
lblfotos = Entry(fotos, textvariable=fotografias)
lblfotos.config(width="75")
lblfotos.place(x=10,y=0)
fotografias.set(listdir(ruta))
raiz.mainloop()
https://i.stack.imgur.com/JaEek.png
[1]: P.S. The original idea is that the files in the folder are displayed in the interface and you can interact with them, such as opening or deleting, but I didn't find how, could that be done in tkinter? or maybe in another library?. Thank you for your answer.
An Entry widget can only hold single line of string. Use Listbox widget instead. Also avoid using wildcard import and it is better to use pack() or grid() instead of place() in normal case.
Below is an example based on your code:
import tkinter as tk
from os import listdir
raiz = tk.Tk()
ruta = './imagenes'
fotos = tk.Frame(raiz, bd=10, relief="groove")
fotos.pack(fill="both", expand=1)
lblfotos = tk.Listbox(fotos, width=30, height=20)
lblfotos.pack(fill="both", expand=1)
for imgfile in listdir(ruta):
lblfotos.insert("end", imgfile)
raiz.mainloop()
I have seen many postings on the use of askopenfilename(), however I still can't seem to find anything to help me display the full file path in an entry box once I have selected said file. below I have included where I have left off.
from tkinter import *
from tkinter.filedialog import askopenfilename
global a
def browse():
a = askopenfilename(title='select new file')
root = Tk()
a = StringVar()
l = Label(root, text="new file: ")
l.pack()
e = Entry(root, width=25, textvariable=a)
e.pack()
b = Button(root, text="Browse", command=browse)
b.pack()
root.mainloop()
Inside your browse function the local variable a does indeed contain the full path to your file. THe issue is that you have to call the StringVar's .set() method, you can't just assign to the variable you bound to the StringVar. Replace a = askopenfilename(title='select new file') with a.set(askopenfilename(title='select new file')) and you will see the filename appear in the StringVar in your interface.
Please note that your program is not well-structured for a GUI interface task, but I presume at present your major difficulty is learning to use the primitives.