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)
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()
So when I create a window and add an image it works. But then I create a window inside a function and it shows image "pyimage2" doesn't exist. I tried adding the image as a global variable but that doesn't work either (Read on another post that it's a possible fix).
Without global variable:
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
With global variable:
import tkinter as tk
import os
global bg
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
global bg
anotherwindow=tk.Tk()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
Posted here: Why photoimages don't exist?
"The second class I defined was the problem cause it used another root window, alias Tk(). An equivalent to the normal Tk() window is the Toplevel() that is the same as a root but hasn't its own interpreter context."
Change the second window to TopLevel().
import tkinter as tk
import os
os.chdir("C:/Users/flare/Desktop/moi/folders/some_files/soundbar program/")
main=tk.Tk()
background=tk.PhotoImage(file="resources/dark_grey_bg.png")
background_label=tk.Label(main,image=background)
background_label.place(x=0,y=0)
def another():
anotherwindow=tk.Toplevel()
bg=tk.PhotoImage(file="resources/light_grey_bg.png")
bg_label=tk.Label(anotherwindow,image=bg)
bg_label.place(x=0,y=0)
anotherwindow.mainloop()
another()
main.mainloop()
Using Tkinter, os, and, pygame modules im finding all files and making a button to play the file because it will be an mp3 file but every time the function overwrites itself so I want to be able to write a function but inside the command parameter in the Tkinter button so it isn't a function but it operates like one
the code i already have:
import os
import pygame
import tkinter as tk
dir_path = os.path.dirname(os.path.realpath(__file__))
d = dir_path+"\\mp3s"
root = tk.Tk()
frame=tk.Frame(root)
root.title("title")
frame.pack()
for path in os.listdir(d):
full_path = os.path.join(d, path)
full_name = os.path.basename(full_path)
def playsong():
pygame.init()
pygame.mixer.music.load(full_path)
pygame.mixer.music.play()
play = tk.Button(frame,
text=full_name,
command=playsong)
play.pack()
root.mainloop()
the function inside the for statement is getting overwritten and I knew this would happen but I was still going to try this works for one file but I want a bunch of different files inside of the folder named "mp3s"
the rest of the code works this is the part that does not
def playsong():
pygame.init()
pygame.mixer.music.load(full_path)
pygame.mixer.music.play(
I wanted to run multiple functions in a line more specifically than lines and I figured out how to do this using lambda
import tkinter as tk
root = tk.Tk()
frame=tk.frame(root)
button = tk.Button(frame, text="name", command= lambda: [func1(), func2()])
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()
I'm still quiet new to programming, so maybe my question in pretty easy or even stupid. As said in the title I'm trying to programm a for loop, which creates a pictured button widget for each picuture in a certain folder. This is what I have so far:
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for file in list_files:
if file.endswith(".gif"):
drink = PhotoImage(file)
print(drink)
b1 = ttk.Button(image=drink, text="Hello", compound="right").pack()
l1 = ttk.Label(image=drink).pack()
root.mainloop()
Now what I get is two widgets, one label displaying nothing and a button displaying Hello. In the shell it says drink1.gif, which is correct, because that's the only gif file in my standard python folder...
what have I done wrong?
Use PhotoImage(file='path_to_file') to create image from path.
When PhotoImage object is garbage-collected by Python, the label is cleared. You must save reference to drink object somewhere: l1.image = drink:
http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
widget.pack() method return nothing.
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os
root = tkinter.Tk()
list_files = os.listdir(".")
for path in list_files:
if path.endswith(".gif"):
drink = PhotoImage(file=path)
b1 = ttk.Button(root, image=drink, text="Hello", compound="right")
b1.pack()
l1 = ttk.Label(root, image=drink)
l1.image = drink
l1.pack()
root.mainloop()
PhotoImage(file) creates an image and gives it the name "drink1.gif", which is returned. If you actually want to load the file into the image, you need PhotoImage(file = file).
I believe you are supposed to run self.pack, according to the Zetcode tutorial.