import time
from pygame import mixer
from tkinter import filedialog, Tk, BOTH
from tkinter.ttk import Frame, Button
from tkinter import *
def playFile(filePath, interval = 5, playTime = 60):
playCount = int(playTime//interval)
for play in range(0, playCount):
mixer.init()
mixer.music.load(filePath)
mixer.music.play()
time.sleep(interval*60)
global clicked
clicked = False
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
return fileLocation
file = ''
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Interval Player")
self.pack(fill=BOTH, expand = 1)
openButton = Button(self, text = "Open", command=findFile)
openButton.place(x=0, y=0)
def main():
root = Tk()
root.geometry("250x150+300+300")
if clicked == True:
file = str(openButton.invoke())
playFile(file)
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
When I choose to invoke the results of the button, the file explorer window opens before openButton has been clicked. How do I make the program wait for button press before invoking the value from the button?
I have tried using a global variable with True/False to find if the button has been clicked. However, I feel like the program is not repeatedly checking for this boolean. Maybe there is a specific function where the playFile has to be added?
your code
if clicked == True:
file = str(openButton.invoke())
playFile(file)
is never used.
what you need to do is act after the message box popup
therefore
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
return fileLocation
becomes
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
if fileLocation:
playFile(fileLocation)
return fileLocation
Full working example
import time
from pygame import mixer
from tkinter import filedialog, Tk, BOTH
from tkinter.ttk import Frame, Button
from tkinter import *
def playFile(filePath, interval = 5, playTime = 60):
playCount = int(playTime//interval)
for play in range(0, playCount):
mixer.init()
mixer.music.load(filePath)
mixer.music.play()
time.sleep(interval*60)
global clicked
clicked = False
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
playFile(fileLocation)
return fileLocation
file = ''
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Interval Player")
self.pack(fill=BOTH, expand = 1)
openButton = Button(self, text = "Open", command=findFile)
openButton.place(x=0, y=0)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
Related
How do I force the button to change its text to the filename? Everything works fine, a dialog box opens and files open too. But I still can't change the button name to the file name and save it.
Here is the code:
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
You can set the buttons text property using.
button['text'] = fileName
You can also read the button text propeerty to make sure it has been set to the file name in code, I.e. with an if statement.
bText = button['text']
Try using .config -
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1.config(text=file_name) # Configure the button's text
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
But if you run this code, the button name gets changed to the complete pathname (e.g. - C:/.../Choosen.file), so if you want only the file name ('Choosen.file') then use this -
btn1.config(text=file_name.split('/')[-1])
You can use:
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1["text"] += " '" + file_name + "'"
os.startfile(file_name)
btn1 = tk.Button(window, text="Open file", command=open) # button
btn1.place(x=20, y=25)
tk.mainloop()
This uses the old text of the button and appends '{file_path}' to it -> Open file '{file_path}'
You could define a new class that maintains state. This way you can avoid the global, and will be able to make multiple buttons each with their own files.
class FileButton(tk.Button):
def __init__(self, window, file_name=""):
super().__init__(window, command=self.open)
self.set_text(file_name)
def set_text(self, file_name):
self.file_name = file_name
self["text"] = f"Open {self.file_name}"
def open(self):
if self.file_name == "":
self.set_text(tfd.askopenfilename())
os.startfile(self.file_name)
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
btn1 = FileButton(window)
btn1.place(x=20, y=25)
window.mainloop()
I have changed everything on other answers but nothing works.
from tkinter import *
import tkinter as tk
import tkinter
import pynput
from pynput.keyboard import Key, Listener
from tkinter import filedialog
charCount = 0
keys = []
press_value = 0
root = Tk()
my_menu = Menu(root)
root.config(menu=my_menu)
def label1(root):
label = tkinter.Label(root, text = "correct")
label.pack()
def pressOn():
button_1.configure(fg = "Green", text = "ON")
def pressOff():
button_1.configure(fg = "red", text = "OFF")
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=1)
def save_location():
location_window = Tk()
var = StringVar()
var.set('No Folder Selected')
locationLabel = Label(location_window, textvariable=var.get())
locationLabel.place(x=70,y=20)
location_window.update()
def browse_button():
filename = filedialog.askdirectory()
print(filename)
var = filename
button2 = Button(location_window, text="Browse", command=browse_button).grid(row=1, column=0)
location_window.title('Save Location')
location_window.iconbitmap('C:/Users/Gaming/Downloads/floppydisk.ico')
location_window.geometry('250x100')
location_window.mainloop()
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New...", command=label1)
file_menu.add_command(label="Exit", command=root.quit)
#Create an edit menu item
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Save Location", command=save_location)
edit_menu.add_command(label="Copy", command=label1)
def buttonPress():
global press_value
press_value = press_value + 1
if (press_value % 2) == 0:
pressOff()
else:
pressOn()
button_1 = tkinter.Button(text="OFF", width = '10', height = '10', fg = 'red', command = buttonPress)
button_1.pack(side = 'bottom')
If you click 'edit' and then'save location'. It pops up with a box but should show a label about the directory people can choose by picking the browse button. It is not working though, the label is not showing. Thanks for everyone's help in advance.
I created a simple program to convert video to audio, using the moviepy library and the program as follows:
import moviepy.editor as mp
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import asksaveasfile, askopenfile
from tkinter.messagebox import showerror
def Open():
video_path = askopenfile(initialdir = "Video", title = "Open Video", filetypes = (("Video", "*.MP4;*.AVI;*.WAV;*.MKV;*.webm;*.TS;*.ASF;*OOG"), ("All files", "*.*")))
try:
open(video_path.name, "r")
ent_mp4.delete(0, END)
ent_mp4.insert(0, video_path.name)
except:
pass
def save_in():
if not(ent_mp4.get() == ""):
saveas = asksaveasfile(initialdir = "Music", title = "Save in", filetype = [("Aduio", "*.MP3;*.FLAC;*.CD;*.WMV"), ("All filest", "*.*")])
ent_mp3.delete(0, END)
ent_mp3.insert(0, saveas.name)
else:
showerror("Error: Empty Entry", "Pleas Enter Your Video Path")
def convert():
video = ent_mp4.get()
music = ent_mp3.get()
if not(music == ""):
root.destroy()
clip = mp.VideoFileClip(video)
clip.audio.write_audiofile(music)
main()
else:
showerror("Error: Empty Entry", "Pleas Enter Your Music Path")
ent_mp4, ent_mp3, root = None, None, None
bu1, bu2, bu3 = None, None, None
def main():
global ent_mp3, ent_mp4, root, bu1, bu2, bu3, sv
root = Tk()
root.title("Convert Video to Audio")
ent_mp4 = ttk.Entry(root, width = 50)
ent_mp4.grid(row = 0, column = 0)
ent_mp3 = ttk.Entry(root, width = 50)
ent_mp3.grid(row = 1, column = 0)
ttk.Button(root, text = "Open video", command = lambda: Open()).grid(row = 0, column = 1)
ttk.Button(root, text = "Save in", command = lambda: save_in()).grid(row = 1, column = 1)
f = ttk.Frame(root)
f.grid(row = 2, column = 0, columnspan = 2)
ttk.Button(f, text = "Convert", command = lambda: convert()).pack(side = LEFT)
ttk.Button(f, text = "Exit", command = lambda: exit()).pack(side = RIGHT)
root.mainloop()
main()
The program is successful but I just want to add something simple, which is that instead of removing the window when the root.destroy () switching process is running, an animated GIF is added that indicates that the process is in progress
I suspect that the solution is to apply two things at the same time for the process to succeed
But I didn't find how to try the "with" command but it didn't work out
So what is the solution
Threading will alow two or more functions to run simultaneously.
from threading import Thread
def func1():
print('Working')
def func2():
print('Working')
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
This is probably a newbie question but I'm having issues figuring out how to get a value from a function, to be used as input in another.
I would also like to have some tips about code organization.
In this example I'm trying to get the filePath and outPut Folder path to be used in the function processFile.
Thank you
Code:
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
numero = str(1)
def OpenFile():
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return fileName
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
def processFile(inFile,outFolder):
''' print(fileName) get input name and output variables
print(outPath)'''
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = processFile)#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
If you use the function in a variable the returned result from the function is stored in the variable.
def Function1(x):
return x*2
var1 = Function1(5)
Then var1 = 10.
But about your buttons, do you want to take input from the user that will be saved when the button is pressed or do you want the button to send a set value?
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return str(fileName)
#getOutputPath
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
I cant see that you have declared the global fileName variabel outside the function.
I did this
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
fileName = "test"
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
test()
return str(fileName)
#getOutputPath
def test():
print(fileName)
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
And the test function prints the chosen file. So the global variable is now containing the correct value.
So just declare it at the top and you will be able to retrieve the value
I am making a development environment type program with python and have a basic working program but I have a problem. I want to highlight certain words like import in a different color, like most development environments do but it wont work!
from tkinter import filedialog
from gameplay import *
from tkinter import *
import msvcrt as m
import os
openfileloc = ""
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def load_file():
rootFd = Tk()
rootFd.withdraw()
file_path = filedialog.askopenfilename()
data = open(file_path, "r").read()
txtFd.delete('1.0', END)
txtFd.insert('1.0', data)
openfile = data
openfileloc = file_path
def save_file_dialog():
rootFd = Tk()
rootFd.withdraw()
wr = filedialog.asksaveasfile(mode='w', defaultextension=".br")
if wr.name != '':
wr.write(txtFd.get('1.0', "end"))
openfileloc = wr.name
wr.close()
def save_file():
if os.path.isfile(openfileloc):
os.remove(file_path)
wr = open(openfileloc, "w").write(txtFd.get('1.0', "end"))
else:
save_file_dialog()
def new_file():
txtFd.delete('1.0', END)
openfile = ""
openfileloc = ""
# HEY STACKOVERFLOW PROBLEM IS HERE
def highlightKeywords():
text = txtFd,get('1.0', 'end')
KeywordSet1 = ['import', 'if'] # Hilighted in Yellow
for i in range(len(text)):
if KeywordSet[i] in text:
txtFd.highlight_pattern(KeywordSet1[i], "yellow")
root = Tk()
root.title("GameBox Engine Editior - 0.0a")
menubar = Menu(root)
#Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=new_file)
filemenu.add_command(label="Open", command=load_file)
filemenu.add_command(label="Save", command=save_file)
filemenu.add_command(label="Save as...", command=save_file_dialog)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
txtFd = Text(root)
txtFd.pack()
root.mainloop()
# THIS IS WHERE I CALL THE FUNCTION
running = True
while(running):
m.getch()
highlightKeywords()
There are no errors, it just does not work. Can you help me?
Use (from http://effbot.org/tkinterbook/text.htm)
text.tag_configure('color', foreground='blue')
text.insert(END, "This is blue\n", 'color')
## you can also use relative position
text.tag_add('color', "1.0", "1.4")