Is there a way to add audio to Tkinter video player? - python

When I run this code a window pops up and I can upload a video of which I can play/stop/pause the video; however the video will not have sound. Is there any way I can solve this issue? I am new to Python. Thanks.
from tkinter import *
from tkinter.filedialog import askopenfile
from tkVideoPlayer import TkinterVideo
# customtkinter.set_appearance_mode("System") # Modes: system (default), light, dark
# customtkinter.set_default_color_theme("blue") # Themes: blue (default), dark-blue, green
# create box
window = Tk()
# title of the box, not the text in the box
window.title("Tkinter Play Videos in Video Player")
window.geometry("700x450")
window.configure(bg="white")
def open_file():
file = askopenfile(mode='r', filetypes=[
('Video Files', ["*.mp4"])])
if file is not None:
global filename
filename = file.name
global videoplayer
videoplayer = TkinterVideo(master=window, scaled=True)
videoplayer.load(r"{}".format(filename))
videoplayer.pack(expand=True, fill="both")
videoplayer.play()
def playAgain():
print(filename)
videoplayer.play()
def StopVideo():
print(filename)
videoplayer.stop()
def PauseVideo():
print(filename)
videoplayer.pause()
# center this label
lbl1 = Label(window, text="Video Player", bg="white",
fg="blue", font="none 24 bold")
lbl1.config(anchor=CENTER)
lbl1.pack()
openbtn = Button(window, text='Open', command=lambda: open_file())
openbtn.pack(side=TOP, pady=2)
playbtn = Button(window, text='Play Video', command=lambda: playAgain())
playbtn.pack(side=TOP, pady=3)
stopbtn = Button(window, text='Stop Video', command=lambda: StopVideo())
stopbtn.pack(side=TOP, padx=4)
pausebtn = Button(window, text='Pause Video', command=lambda: PauseVideo())
pausebtn.pack(side=TOP, padx=5)
window.mainloop()
The result video does not have audio.

Related

unable to execute the tkinter stegano / unable to execute/install the steganograph project & unable to install the PIL package

unable to execute the tkinter stegano / unable to execute/install the steganograph project & unable to install the PIL package
unable to execute the tkinter stegano / unable to execute/install the steganograph project & unable to install the PIL package
from tkinter import *
from tkinter import filedialog
import tkinter as Tk
from PIL import Image, ImageTk
import os
from stegano import lsb
root = Tk()
root.title("Steganography - Hide a Secret Text Message in an Image")
root.geometry("700x500+150+180")
root.resizable(False, False)
root.configure(bg="#2f4155")
def showimage():
global filename
filename = filedialog.askopenfilename(initialdir=os.getcwd(),
title='Select Image File',
filetype=(("PNG file", "*.png"),
("JPG File", "*.jpg"), ("All file", "*.txt")))
img = Image.open(filename)
img = ImageTk.PhotoImage(img)
lbl.configure(image=img, width=250, height=250)
lbl.image = img
def hide():
global secret
message = text1.get(1.0, END)
secret = lsb.hide(str(filename), message)
def show():
clear_message = lsb.reveal(filename)
text1.delete(1.0, END)
text1.insert(END, clear_message)
def save():
secret.save("hidden.png")
# icon
image_icon = PhotoImage(file="10211761.jpg")
root.iconphoto(False, image_icon)
# logo
logo = PhotoImage(file="33412325.jpg")
Label(root, image=logo, bg="#2f4155").place(x=10, y=0)
Label(root, text="CYBER SCIENCE", bg="#2d4155", fg="white", font="arial 25 bold").place(x=100, y=20)
# first Frame
f = Frame(root, bd=3, bg="black", width=340, height=280, relief=GROOVE)
f.place(x=10, y=80)
lbl = Label(f, bg="black")
lbl.place(x=40, y=10)
# Second Frame
frame2 = Frame(root, bd=3, width=340, height=280, bg="white", relief=GROOVE)
frame2.place(x=350, y=80)
text1 = Text(frame2, font="Roboto 20", bg="white", fg="black", relief=GROOVE, wrap=WORD)
text1.place(x=0, y=0, width=320, height=295)
scrollbar1 = Scrollbar(frame2)
scrollbar1.place(x=320, y=0, height=300)
scrollbar1.configure(command=text1.yview)
text1.configure(yscrollcommand=scrollbar1.set)
# third Frame
frame3 = Frame(root, bd=3, bg="#2f4155", width=330, height=100, relief=GROOVE)
frame3.place(x=10, y=370)
Button(frame3, text="Open Image", width=10, height=2, font="arial 14 bold", command=showimage).place(x=20, y=30)
Button(frame3, text="Save Image", width=10, height=2, font="arial 14 bold", command=save).place(x=180, y=30)
Label(frame3, text="Picture, Image, Photo File", bg="#2f4155", fg="yellow").place(x=20, y=5)
# fourth Frame
frame4 = Frame(root, bd=3, bg="#2f4155", width=330, height=100, relief=GROOVE)
frame4.place(x=360, y=370)
Button(frame4, text="Hide Data", width=10, height=2, font="arial 14 bold", command=hide).place(x=20, y=30)
Button(frame4, text="Show Data", width=10, height=2, font="arial 14 bold", command=show).place(x=180, y=30)
Label(frame4, text="Picture, Image, Photo File", bg="#2f4155", fg="yellow").place(x=20, y=5)
/Users/monesh/PycharmProjects/Steganograph/venv/bin/python /Users/monesh/PycharmProjects/Steganograph/main.py
Traceback (most recent call last):
File "/Users/monesh/PycharmProjects/Steganograph/main.py", line 8, in <module>
root = Tk()
TypeError: 'module' object is not callable
Process finished with exit code 1
-- unable to execute/install the steganograph project & unable to install the PIL package --

How do i open a new window on the click of a button with tkinter?

I am making a text base game and would like to get a new root window on the click of a button while simultaneously closing the original one?
#Packages
import tkinter as tk
from tkinter import ttk, BOTTOM
from PIL import ImageTk, Image
#Create Window
root = tk.Tk()
root.geometry("360x740")
root.resizable(True, True)
root.title("Box")
root.configure(bg="black")
#Load Image
canvas = tk.Canvas(root, width=360, height=360, bg="black")
tk.Canvas(bg="black")
canvas.pack()
img = ImageTk.PhotoImage(Image.open("sample_image.jpg"))
canvas.create_image(180, 200, image=img)
#Create Text Widget
T = tk.Text(root, height=10, width=52, bg="black", fg="white")
l = tk.Label(root, text="Hard Living by Amsha", fg="white", bg="black")
l.config(font=(None, 14,))
story = """
"""
l.pack()
T.pack()
#Continue Button
yes_button = ttk.Button(root, text="Continue", command=lambda: next_window())
yes_button.pack(pady=75, side=BOTTOM)
T.insert(tk.END, story)
root.mainloop()
def next_window():
root.quit()
root = tk.Tk()
root.geometry("360x740")
root.resizable(True, True)
root.title("Hard Living")
root.configure(bg="black")
root.mainloop()

alright this is weird Python

so ok i was just using TKInter when i got this error NameError
name 'runApps' is not defined
import tkinter as tk
from tkinter import filedialog, Text
import os
root = tk.Tk()
apps = []
def addApp():
for widget in frame.winfo_children():
widget.destroy()
filename = filedialog.askopenfilename(initialdir="/", title="Select File",
filetypes=(("executables","*.exe"), ("all files", "*.*")))
apps.append(filename)
print(filename)
for app in apps:
label = tk.Label(frame, text=app, bg="gray")
label.pack()
def runApps():
for app in apps:
os.startfile(app)
canvas = tk.Canvas(root, height=700, width=700, bg="#163542")
canvas.pack()
frame = tk.Frame(root, bg="green")
frame.place(relwidth=0.4, relheight=0.4, relx=0.3, rely=0.25)
openFile = tk.Button(root, text="Open File", padx=10,
pady=5, fg="white", bg="#163542" ,command=addApp)
openFile.pack()
runApps = tk.Button(root, text="Run Apps", padx=10,
pady=5 , fg="white", bg="#163542" , command = runApps)
runApps.pack()
root.mainloop()
ok if anyone knows how to fix this make a comment or answer
this section for this post is only for ShanyeLoyd
here is the post you wanted ShanyeLoyd
If you fix the indents in your code then it works.
As per the official documentation:
Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.
Correct formatted code:
import tkinter as tk
from tkinter import filedialog
import os
root = tk.Tk()
apps = []
def addApp():
for widget in frame.winfo_children():
widget.destroy()
filename = filedialog.askopenfilename(
initialdir="/",
title="Select File",
filetypes=(("executables", "*.exe"), ("all files", "*.*")),
)
apps.append(filename)
print(filename)
for app in apps:
label = tk.Label(frame, text=app, bg="gray")
label.pack()
def runApps():
for app in apps:
os.startfile(app)
canvas = tk.Canvas(root, height=700, width=700, bg="#163542")
canvas.pack()
frame = tk.Frame(root, bg="green")
frame.place(relwidth=0.4, relheight=0.4, relx=0.3, rely=0.25)
openFile = tk.Button(
root, text="Open File", padx=10, pady=5, fg="white", bg="#163542", command=addApp
)
openFile.pack()
runApps = tk.Button(
root, text="Run Apps", padx=10, pady=5, fg="white", bg="#163542", command=runApps
)
runApps.pack()
root.mainloop()
GUI:

Updating label text in frame when job is finished

When pressing "Ping test" you get a new 'main window' with input and submit button.
when Submit is clicked, a file is created on the desktop and writes the output result of ping command.
right now, when I enter an address and click submit, I only see the menu frame and the main frame, the output frame shows up when the proccess is finished.
how can I make the output frame show "Pinging..." when I click the Submit button and update the label to "Ping Complete!" when its finished?
here's my code:
import tkinter as tk
import subprocess as sub
import easygui
import os
root = tk.Tk()
root.geometry("400x300")
# ===== Frame 1 - Left Menu =====
frame = tk.LabelFrame(root, text="Menu",height=80, width=40,
padx=5, pady=5, relief="solid")
frame.place(x=10, y=0)
# Show files button
showfilesButton = tk.Button(frame, text="Show Files", padx=5, pady=5,
command=lambda: showFiles())
showfilesButton.grid(row=1, column=0)
# ConvertURL button
convertURL = tk.Button(frame, text="Ping Test", padx=5, pady=5,
command=lambda: testPing.getURL())
convertURL.grid(row=2, column=0)
# Quit Button
endProgram = tk.Button(frame, text="Quit", padx=5, pady=5,
command=lambda: terminate())
endProgram.grid(row=3, column=0)
class testPing():
def __init__(self, host):
self.host = host
self.clearFile = clearFile
self.label = label
def getURL():
frame2 = tk.LabelFrame(root, text="Main Window", height=350, width=300, padx=30, pady=30)
frame2.pack()
urlLabel = tk.Label(frame2, text="Enter URL : ", padx=5, pady=5)
urlLabel.place(x=-30, y=-30)
urlInputBox = tk.Entry(frame2)
urlInputBox.pack()
clearLabel = tk.Label(frame2, text="Clear File?", padx=5, pady=5)
clearLabel.place(x=-30, y=20)
clearFile = tk.BooleanVar()
clearFile.set(False)
clearFileRadioYes = tk.Radiobutton(frame2, text="yes", value=True, var=clearFile,
command=lambda: testPing.callback(clearFile.get()))
clearFileRadioYes.place(x=-30, y=45)
clearFileRadioNo = tk.Radiobutton(frame2, text="no", value=False, var=clearFile,
command=lambda: testPing.callback(clearFile.get()))
clearFileRadioNo.place(x=20, y=45)
urlSubmitButton = tk.Button(frame2, text="Submit",
command=lambda: testPing.pingURL(urlInputBox.get(), clearFile.get()))
urlSubmitButton.pack(side=tk.RIGHT)
def callback(clearFile):
bul = clearFile
print(bul)
def pingURL(host, clearFile):
outputLabel = tk.LabelFrame(root, text="Output", height=35, width=150,
padx=5, pady=5, relief="solid")
outputLabel.place(x=0, y=150)
file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
label = tk.Label(outputLabel, text=f'Pinging {host} ...')
label.grid(row=0, column=0)
clear = clearFile
if clear == True:
with open(file, 'w+') as output:
output.truncate(0)
sub.call(['ping', f'{host}'], stdout=output)
else:
with open(file, 'a') as output:
sub.call(['ping', f'{host}'], stdout=output)
output.close()
# testPing.changeLabel(host)
def changeLabel(host):
myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
myLabel.pack()
def terminate():
exit()
def showFiles():
path = easygui.diropenbox() # Opens a folder dialog box.
folder = path
filelocation = f"c:\\Users\\{os.getlogin()}\\Desktop\\showFilesResult.txt"
filenames = os.listdir(folder) # Get the file names in the folder.
# Writing to file
with open(filelocation, 'a') as file:
for name in filenames:
file.write(f"Name: {name}\nFolder Path: {folder}\n!------------------------------!\n")
print("Done!")
root.mainloop()
Instead of calling changeLabel(), you can simply put:
output.close()
label.configure(text=f'Ping to {host} complete!')
# testPing.changeLabel(host)
But remember about updating your label first, if you don't at the end only complete label will be visible.
label = tk.Label(outputLabel, text=f'Pinging {host} ...')
label.grid(row=0, column=0)
label.update()
An additional tip, don't use different GUI creators in one project. If you only using easygui to get the path, check Tkinter methods -> askopenfilename and asksaveasfilename.

How to create a download bar in python

So I am working on this program that is supposed to be downloading stuff from the web using tkinter and urllib.request but it is lacking a download bar(or a progress bar if that is the true word). So I found out that you can create a progress bar using TQDM but there are two problems: first of all, I didn't seem to find a way to use it in a tkinter program. Second of all, It doesn't show the download speed, you just set a limit and it fills up until it reaches that limit. I did a bit of research again and I found out that you can create a progress bar using ttk but it still has the second problem(It does not show the user's internet(download) speed and that how much of the file has been downloaded like chrome's download bar).
Can someone help me out on this?
My code(BTW if you have any suggestions how to make my program better I would appreciate it):
from tkinter import *
from tkinter import font as tkFont
import random
import urllib.request
import requests
from tqdm import tqdm
from tqdm.auto import tqdm
def printsth():
print("Yay it works! ")
def main_menu():
root = Tk()
# the top menu
num = IntVar()
# var = IntVar()
menu = Menu(root)
root.config(menu=menu)
submenu = Menu(menu)
menu.add_cascade(label="Settings", menu=submenu)
def custom_op():
custom = Tk()
custom.mainloop()
submenu.add_command(label="Customization ", command=custom_op)
def settings_op():
set_win = Tk()
set_win.mainloop()
submenu.add_command(label="Settings ", command=settings_op)
submenu.add_separator()
submenu.add_command(label="Exit", command=root.destroy)
# the edit menu
editmenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editmenu)
editmenu.add_command(label="Redo...", command=printsth)
# the tool bar
toolbar = Frame(root, bg="light gray")
insert_button = Button(toolbar, text="Insert an image", command=printsth)
insert_button.pack(side=LEFT, padx=2, pady=2)
print_button = Button(toolbar, text="Print", command=printsth)
print_button.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
# the download function
def download_image():
global formatname
if num.get() == 1:
name = random.randrange(1, 100000)
else:
name = str(name_entry.get())
formatname = str(format_entry.get())
'''if var.get() == 1:
operator = str(url_entry.get())
formatname = '.' + operator[-3] + operator[-2] + operator[-1]
else:
pass'''
fullname = str(name) + formatname
url = str(url_entry.get())
fw = open('file-size.txt', 'w')
file_size = int(requests.head(url, headers={'accept-encoding': ''}).headers['Content-Length'])
fw.write(str(file_size))
fw.close()
path = str(output_entry.get()) + "\\"
urllib.request.urlretrieve(url, path.replace("\\", "\\\\") + fullname)
# the status bar
status_bar = Label(root, text="Downloading...", bd=1, relief=SUNKEN, anchor=W)
status_bar.pack(side=BOTTOM, fill=X)
# the download frame
body_frame = Frame(root, bg="light blue")
download_button = Button(body_frame, text="Download! ", command=download_image, border=3, width=20, height=5)
download_design = tkFont.Font(size=12, slant='italic')
download_button['font'] = download_design
download_button.pack(side=LEFT, pady=5, padx=5)
body_frame.pack(side=LEFT, fill=Y)
# the main interaction menu
inter_frame = Frame(root)
url_entry = Entry(inter_frame)
label = Label(inter_frame, text="Enter the image URL: ")
file_format = Label(inter_frame, text="Choose your file format: ")
format_entry = Entry(inter_frame)
file_name = Label(inter_frame, text="File's name: ")
name_entry = Entry(inter_frame)
check_name = Checkbutton(inter_frame, text="Give a random name", variable=num)
# check_format = Checkbutton(inter_frame, text="Download with default format", variable=var)
output_path = Label(inter_frame, text="Choose output path: ")
output_entry = Entry(inter_frame)
file_name.pack(anchor=CENTER, expand=1)
name_entry.pack(anchor=CENTER, expand=1)
check_name.pack(anchor=CENTER, expand=1)
label.pack(anchor=CENTER, expand=1)
url_entry.pack(anchor=CENTER, expand=1)
file_format.pack(anchor=CENTER, expand=1)
format_entry.pack(anchor=CENTER, expand=1)
# check_format.pack(anchor=CENTER)
output_path.pack(anchor=CENTER, expand=1)
output_entry.pack(anchor=CENTER, expand=1)
inter_frame.pack(expand=1)
root.mainloop()
# the end!
main_menu()
This is code snippet from my tool for status bar
progress = ttk.Progressbar(self, orient=HORIZONTAL, length=400, mode='determinate')
progress.grid(row=3, column=0, pady=2, padx=2, columnspan=4, sticky=SW+SE)
progress.pack(side=BOTTOM, anchor=S, expand=YES)
progress["maximum"] = 100
progerss_part = 0
you can update progress by using
progress["value"] = x
Hope this will help you.

Categories

Resources