how to run multiple lines with variables in tkinter - python

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

Related

Tkinter getting file path returned to main function to use and pass on to other functions

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 am trying to make a exe similar to windows file explorer with python using os.path and tkinter

from PIL import Image
from tkinter import filedialog as fd
import os
import ctypes
import tkinter
class ImageList:
path = ""
dir = ""
top = tkinter.Tk()
canvas = tkinter.Canvas()
canvas.pack()
def __init__(self):
self.path = os.path.expanduser('~/')
def findImage(self):
image = Image.open(self.dir, "rb")
image.show()
def fileExplorer(self, path):
self.canvas.destroy()
self.canvas = tkinter.Canvas()
self.canvas.pack()
obj = os.scandir(path)
for entry in obj:
if entry.is_dir():
#self.path = os.path.abspath(self.path)
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: self.fileExplorer(os.path.abspath(entry).replace('//', '\\')))
b.pack()
elif entry.is_file():
b = tkinter.Button(self.canvas, text=entry.name, command=lambda: print(entry.name))
b.pack()
else:
obj.close()
self.top.mainloop()
As shown in the code above, I am trying to make exe that shows the subdirs and files after C:\Users using buttons in tkinter and repeating it by using recursion.
The first error is that in "os.path.abspath(entry).replace('//', '\')" shows path in a format of "C://Users" and I intended to change that to "C:\Users" using the replace method. However, using "\" doesn't replace "//" and still shows as the original format.
The second error is that after running the code, when I press any button it acts as if I pressed the last button in the tkinter window, meaning that it recursively called the last subdir or the file below "C:\Users".
I'm just getting used to python and this is my first time using stackoverflow. I'm sorry if I did not abide by any of the rules in stackoverflow. Thanks for anyone helping.

Trying to get a variable from a function using tkinter

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)

Python - tkinter and glob.glob working togheter

Im new to tkinter and trying to open the explorer (on windows) so that i can chose what folder i want to use in my program. I found a template for tkinter and altered it to work with my function and how i need the filepath to be. Before i tried using tkinter to "select my folder", i had manually writen the directory in the glob.glob function like this glob.glob(r'C:\Users\Desktop\Spyder\*.log') (and it worked). So my new ide was to replace the pathname input from r'C:\Users\Desktop\Spyder\*.log' to a variabel that stored the same pathname but now it used tkinters askdirectory() to finde the directory inteed.
import glob
import os
from itertools import zip_longest
import tkinter as tk
from tkinter import filedialog
#-------------Connect to Access2013------------------
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_folder = tk.Button(self)
self.select_folder["text"] = "Open WindowsExplorer"
self.select_folder["command"] = self.ask_directory_to_folder
self.select_folder.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def ask_directory_to_folder(self):
clerdatabase() # a funktion that resets the autonumber and deleats all data from every table
print("Open!")
filepath = filedialog.askdirectory()
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
#--------------Scan selected folder for .log files and starts to scan files---------
def find_filenames(right_log_filepath): #finds every file in the chosen filepath
print(right_log_filepath) # r'C:\Users\Desktop\Spyder\*.log'
print("ok")
filenames = [] # list for all the found filenames
for filepath_search in glob.glob(str(right_log_filepath), recursive=True): #A for loop that opens every .log file in the chosen directory folder
print('run')
My problem ist that i don´t get the for loop filepath_search to work (it prints "ok"). But the word run inside the for loop dose not print, i guess it´s because it gets stuck somewhere before that? Someone who has more experience with tkinter that can help me? Thanks
I guess issue caused by what is passed to glob.glob since it doesn't find anything. It seems that it is mostly related to the fact that you add ' characters at the beggining and end of your right_log_filepath.
In ask_directory_to_folder function replace:
log_filepath = "r'"+ str(filepath +"/*.log'")
right_log_filepath = log_filepath.replace('/','\ ').replace(' ','')
find_filenames(right_log_filepath)
With:
from os import path # should be at the top of your file
log_filepath = path.join(filepath, "*.log")
find_filenames(log_filepath)

Python-Tkinter, for-loop to create pictured button

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.

Categories

Resources