提问人:Defiant Softs 提问时间:11/16/2023 最后编辑:toyota SupraDefiant Softs 更新时间:11/16/2023 访问量:40
如何使用特定按钮将不同的 Tkinter 文件合并到一个文件中
How to combine different Tkinter files in a single file with specific buttons
问:
我在 tkinter python 中创建了音频播放器、视频播放器、音频剪辑器、视频转换器和视频增强器。上述所有应用程序都有单独的文件。我有一个根窗口代码,我在其中设计了一个具有 6 个按钮的窗口,对应于上述应用程序。我只想将代码组合到一个(根)窗口/文件中。 我的意思是,带有 6 个按钮的根窗口将是主窗口。当用户单击任何按钮时,该应用文件的代码将运行,用户可以执行任务。 我拥有所有源代码,但我无法将其组织在一个文件中。 如何将该代码与根窗口结合使用?
所有代码如下: 音频播放器:
from tkinter import *
from tkinter import filedialog
import pygame
import time
from mutagen.mp3 import MP3
import tkinter.ttk as ttk
import os
root = Tk()
root.title("MP3 Player")
root.geometry("500x400")
# Initialize Pygame
pygame.mixer.init()
# Create Function To Deal With Time
def play_time():
# Check to see if song is stopped
if stopped:
return
# Grab Current Song Time
current_time = pygame.mixer.music.get_pos() / 1000
# Convert Song Time To Time Format
converted_current_time = time.strftime('%M:%S', time.gmtime(current_time))
# Reconstruct song with directory structure stuff
song = playlist_box.get(ACTIVE)
song = f'{song}.mp3'
# Find Current Song Length
song_mut = MP3(song)
global song_length
song_length = song_mut.info.length
# Convert to time format
converted_song_length = time.strftime('%M:%S', time.gmtime(song_length))
# Check to see if song is over
if int(song_slider.get()) == int(song_length):
stop()
elif paused:
# Check to see if paused, if so - pass
pass
else:
# Move slider along 1 second at a time
next_time = int(song_slider.get()) + 1
# Output new time value to slider, and to length of song
song_slider.config(to=song_length, value=next_time)
# Convert Slider poition to time format
converted_current_time = time.strftime('%M:%S', time.gmtime(int(song_slider.get())))
# Output slider
status_bar.config(text=f'Time Elapsed: {converted_current_time} of {converted_song_length} ')
# Add Current Time To Status Bar
if current_time > 0:
status_bar.config(text=f'Time Elapsed: {converted_current_time} of {converted_song_length} ')
# Create Loop To Check the time every second
status_bar.after(1000, play_time)
# Create Function To Add One Song To Playlist
def add_song():
song = filedialog.askopenfilename(initialdir='audio/', title="Choose A Song", filetypes=(("mp3 Files", "*.mp3" ), ))
# Strip out directory structure and .mp3 from song title
song = song.replace("C:/mp3/audio/", "")
song = song.replace(".mp3", "")
# Add To End of Playlist
playlist_box.insert(END, song)
#add Videos to Player
def open_file(self):
options = {"defaultextension": ".mp3", "filetypes": [("Audio files", "*.mp3;*.wav"),("Video files", "*.mp4;*.avi;*.mkv")]}
filepath = filedialog.askopenfilename(**options)
if filepath:
if filepath.endswith(('.mp3', '.wav')):
self.playlist.insert("", "end", text=os.path.basename(filepath), values=(filepath,))
self.play_audio(filepath)
elif filepath.endswith(('.mp4', '.avi', '.mkv')):
self.play_video(filepath)
#Play Video in Player
def play_video(self, filepath):
pygame.init()
pygame.mixer.quit()
pygame.display.set_caption("Media Player")
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Media Player")
pygame.display.set_caption(filepath)
movie = pygame.movie.Movie(filepath)
movie_screen = pygame.Surface((800, 600))
movie.set_display(movie_screen)
movie.play()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
movie.stop()
pygame.display.quit()
pygame.quit()
exit()
screen.blit(movie_screen, (0, 0))
pygame.display.update()
# Create Function To Add Many Songs to Playlist
def add_many_songs():
songs = filedialog.askopenfilenames(initialdir='audio/', title="Choose A Song", filetypes=(("mp3 Files", "*.mp3" ), ))
# Loop thru song list and replace directory structure and mp3 from song name
for song in songs:
# Strip out directory structure and .mp3 from song title
song = song.replace("C:/mp3/audio/", "")
song = song.replace(".mp3", "")
# Add To End of Playlist
playlist_box.insert(END, song)
# Create Function To Delete One Song From Playlist
def delete_song():
# Delete Highlighted Song From Playlist
playlist_box.delete(ANCHOR)
# Create Function To Delete All Songs From Playlist
def delete_all_songs():
# Delete ALL songs
playlist_box.delete(0, END)
# Create Play Function
def play():
# Set Stopped to False since a song is now playing
global stopped
stopped = False
# Reconstruct song with directory structure stuff
song = playlist_box.get(ACTIVE)
song = f'{song}.mp3'
#Load song with pygame mixer
pygame.mixer.music.load(song)
#Play song with pygame mixer
pygame.mixer.music.play(loops=0)
# Get Song Time
play_time()
# Create Stopped Variable
global stopped
stopped = False
def stop():
# Stop the song
pygame.mixer.music.stop()
# Clear Playlist Bar
playlist_box.selection_clear(ACTIVE)
status_bar.config(text='')
# Set our slider to zero
song_slider.config(value=0)
# Set Stop Variable To True
global stopped
stopped = True
# Create Function To Play The Next Song
def next_song():
# Reset Slider position and status bar
status_bar.config(text='')
song_slider.config(value=0)
#Get current song number
next_one = playlist_box.curselection()
# Add One To The Current Song Number Tuple/list
next_one = next_one[0] + 1
# Grab the song title from the playlist
song = playlist_box.get(next_one)
# Add directory structure stuff to the song title
song = f'{song}.mp3'
#Load song with pygame mixer
pygame.mixer.music.load(song)
#Play song with pygame mixer
pygame.mixer.music.play(loops=0)
# Clear Active Bar in Playlist
playlist_box.selection_clear(0, END)
# Move active bar to next song
playlist_box.activate(next_one)
# Set Active Bar To next song
playlist_box.selection_set(next_one, last=None)
# Create function to play previous song
def previous_song():
# Reset Slider position and status bar
status_bar.config(text='')
song_slider.config(value=0)
#Get current song number
next_one = playlist_box.curselection()
# Add One To The Current Song Number Tuple/list
next_one = next_one[0] - 1
# Grab the song title from the playlist
song = playlist_box.get(next_one)
# Add directory structure stuff to the song title
song = f'{song}.mp3'
#Load song with pygame mixer
pygame.mixer.music.load(song)
#Play song with pygame mixer
pygame.mixer.music.play(loops=0)
# Clear Active Bar in Playlist
playlist_box.selection_clear(0, END)
# Move active bar to next song
playlist_box.activate(next_one)
# Set Active Bar To next song
playlist_box.selection_set(next_one, last=None)
# Create Paused Variable
global paused
paused = False
# Create Pause Function
def pause(is_paused):
global paused
paused = is_paused
if paused:
#Unpause
pygame.mixer.music.unpause()
paused = False
else:
#Pause
pygame.mixer.music.pause()
paused = True
#Create Volume Function
def volume(x):
pygame.mixer.music.set_volume(volume_slider.get())
# Create a Slide Function For Song Positioning
def slide(x):
# Reconstruct song with directory structure stuff
song = playlist_box.get(ACTIVE)
song = f'{song}.mp3'
#Load song with pygame mixer
pygame.mixer.music.load(song)
#Play song with pygame mixer
pygame.mixer.music.play(loops=0, start=song_slider.get())
# Create main Frame
main_frame = Frame(root)
main_frame.pack(pady=20)
# Create Playlist Box
playlist_box = Listbox(main_frame, bg="black", fg="green", width=60, selectbackground="green", selectforeground='black')
playlist_box.grid(row=0, column=0)
# Create volume slider frame
volume_frame = LabelFrame(main_frame, text="Volume")
volume_frame.grid(row=0, column=1, padx=20)
# Create Volume Slider
volume_slider = ttk.Scale(volume_frame, from_=0, to=1, orient=VERTICAL, length=125, value=1, command=volume)
volume_slider.pack(pady=10)
# Create Song Slider
song_slider = ttk.Scale(main_frame, from_=0, to=100, orient=HORIZONTAL, length=360, value=0, command=slide)
song_slider.grid(row=2, column=0, pady=20)
# Define Button Images For Controls
back_btn_img = PhotoImage(file='images/back50.png')
forward_btn_img = PhotoImage(file='images/forward50.png')
play_btn_img = PhotoImage(file='images/play50.png')
pause_btn_img = PhotoImage(file='images/pause50.png')
stop_btn_img = PhotoImage(file='images/stop50.png')
# Create Button Frame
control_frame = Frame(main_frame)
control_frame.grid(row=1, column=0, pady=20)
# Create Play/Stop etc Buttons
back_button = Button(control_frame, image=back_btn_img, borderwidth=0, command=previous_song)
forward_button = Button(control_frame, image=forward_btn_img, borderwidth=0, command=next_song)
play_button = Button(control_frame, image=play_btn_img, borderwidth=0, command=play)
pause_button = Button(control_frame, image=pause_btn_img, borderwidth=0, command=lambda: pause(paused))
stop_button = Button(control_frame, image=stop_btn_img, borderwidth=0, command=stop)
back_button.grid(row=0, column=0, padx=10)
forward_button.grid(row=0, column=1, padx=10)
play_button.grid(row=0, column=2, padx=10)
pause_button.grid(row=0, column=3, padx=10)
stop_button.grid(row=0, column=4, padx=10)
# Create Main Menu
my_menu = Menu(root)
root.config(menu=my_menu)
# Create Add Song Menu Dropdows
add_song_menu = Menu(my_menu, tearoff=0)
my_menu.add_cascade(label="Add Songs", menu=add_song_menu)
# Add One Song To Playlist
add_song_menu.add_command(label="Add One Song To Playlist", command=add_song)
# Add Many Songs to Playlist
add_song_menu.add_command(label="Add Many Songs To Playlist", command=add_many_songs)
# Create Delete Song Menu Dropdowns
remove_song_menu = Menu(my_menu, tearoff=0)
my_menu.add_cascade(label="Remove Songs", menu=remove_song_menu)
remove_song_menu.add_command(label="Delete A Song From Playlist", command=delete_song)
remove_song_menu.add_command(label="Delete All Songs From Playlist", command=delete_all_songs)
# Create Status Bar
status_bar = Label(root, text='', bd=1, relief=GROOVE, anchor=E)
status_bar.pack(fill=X, side=BOTTOM, ipady=2)
# Temporary Label
my_label = Label(root, text='')
my_label.pack(pady=20)
root.mainloop()
视频播放器代码:
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import cv2
from pydub import AudioSegment
from pydub.playback import play
class VideoPlayerApp:
def __init__(self, root):
self.root = root
self.root.title("Video Player")
self.video_frame = ttk.Frame(self.root)
self.video_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.playing = False
self.paused = False
self.video_canvas = tk.Canvas(self.video_frame)
self.video_canvas.pack(fill=tk.BOTH, expand=True)
self.play_pause_button = ttk.Button(self.root, text="Play", command=self.toggle_play_pause)
self.play_pause_button.pack()
self.stop_button = ttk.Button(self.root, text="Stop", command=self.stop)
self.stop_button.pack()
self.volume_scale = ttk.Scale(self.root, from_=0, to=1, orient=tk.HORIZONTAL, command=self.set_volume)
self.volume_scale.set(1)
self.volume_scale.pack()
self.progress_bar = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, mode='determinate')
self.progress_bar.pack(fill=tk.X)
self.load_button = ttk.Button(self.root, text="Load Video", command=self.load_video)
self.load_button.pack()
self.video_path = None
self.video_capture = None
self.video_duration = 0
self.update_progress()
def load_video(self):
self.video_path = filedialog.askopenfilename(filetypes=[("Video files", "*.mp4 *.avi *.mkv")])
if self.video_path:
self.playing = False
self.paused = False
self.play_pause_button.config(text="Play")
self.video_capture = cv2.VideoCapture(self.video_path)
self.video_duration = int(self.video_capture.get(cv2.CAP_PROP_FRAME_COUNT) / self.video_capture.get(cv2.CAP_PROP_FPS))
self.progress_bar.config(maximum=self.video_duration)
self.update_progress()
def toggle_play_pause(self):
if self.video_path:
if self.playing:
self.paused = not self.paused
if self.paused:
self.play_pause_button.config(text="Resume")
else:
self.play_pause_button.config(text="Pause")
else:
self.playing = True
self.play_pause_button.config(text="Pause")
self.play_video()
def play_video(self):
if self.video_capture.isOpened() and (self.playing or self.paused):
ret, frame = self.video_capture.read()
if ret:
self.show_frame(frame)
if not self.paused:
self.progress_bar.step()
self.root.after(int(1000 / self.video_capture.get(cv2.CAP_PROP_FPS)), self.play_video)
else:
self.root.after(100, self.play_video)
else:
self.stop()
messagebox.showinfo("Info", "Video playback finished.")
def stop(self):
self.playing = False
self.paused = False
self.play_pause_button.config(text="Play")
if self.video_capture:
self.video_capture.release()
self.progress_bar.stop()
self.progress_bar.config(value=0)
def set_volume(self, volume):
pass # Implement volume control
def update_progress(self):
pass # No need to update progress here since play_video function takes care of it
def show_frame(self, frame):
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = tk.PhotoImage(data=cv2.imencode('.png', frame)[1].tobytes())
self.video_canvas.create_image(0, 0, anchor=tk.NW, image=img)
self.video_canvas.image = img
if __name__ == "__main__":
root = tk.Tk()
app = VideoPlayerApp(root)
root.mainloop()
Audio Clipper 代码:
from tkinter import *
from tkinter import filedialog
from pydub import AudioSegment
# Function to create a new audio file with the selected range
def create_new_file():
# Get the values entered by the user
file_path = file_path_entry.get()
start_min = int(start_min_entry.get())
start_sec = int(start_sec_entry.get())
end_min = int(end_min_entry.get())
end_sec = int(end_sec_entry.get())
# Open the selected file
song = AudioSegment.from_file(file_path, format="mp3")
# Calculate the start and end times in milliseconds
start = ((start_min * 60) + start_sec) * 1000
end = ((end_min * 60) + end_sec) * 1000
# Extract the selected range from the song
clip = song[start:end]
# Ask the user to select a save location and filename
save_path = filedialog.asksaveasfilename(defaultextension=".mp3")
# Save the extracted clip as a new mp3 file
clip.export(save_path, format="mp3")
# Show a message to indicate that the new file has been created
status_label.config(text="New Audio file is created and saved")
# Create the main window
root = Tk()
root.title("Audio Clipper")
# Create a frame to hold the file path input field and browse button
file_frame = Frame(root)
file_frame.pack(pady=10)
file_path_label = Label(file_frame, text="File Path:")
file_path_label.pack(side=LEFT)
file_path_entry = Entry(file_frame, width=50)
file_path_entry.pack(side=LEFT, padx=10)
browse_button = Button(file_frame, text="Browse", command=lambda: file_path_entry.insert(0, filedialog.askopenfilename()))
browse_button.pack(side=LEFT)
# Create a frame to hold the start/end time input fields
time_frame = Frame(root)
time_frame.pack()
start_label = Label(time_frame, text="Start Time (mm:ss):")
start_label.pack(side=LEFT)
start_min_entry = Entry(time_frame, width=2)
start_min_entry.insert(END, "1")
start_min_entry.pack(side=LEFT)
start_colon_label = Label(time_frame, text=":")
start_colon_label.pack(side=LEFT)
start_sec_entry = Entry(time_frame, width=2)
start_sec_entry.insert(END, "10")
start_sec_entry.pack(side=LEFT)
end_label = Label(time_frame, text="End Time (mm:ss):")
end_label.pack(side=LEFT)
end_min_entry = Entry(time_frame, width=2)
end_min_entry.insert(END, "2")
end_min_entry.pack(side=LEFT)
end_colon_label = Label(time_frame, text=":")
end_colon_label.pack(side=LEFT)
end_sec_entry = Entry(time_frame, width=2)
end_sec_entry.insert(END, "5")
end_sec_entry.pack(side=LEFT)
# Create a button to initiate the audio extraction
extract_button = Button(root, text="Create Audio Clip", command=create_new_file)
extract_button.pack(pady=10)
# Create a label to show the status of the extraction process
status_label = Label(root, text="", fg="green")
status_label.pack()
root.mainloop()
视频转换器代码:
import tkinter as tk
from tkinter import filedialog
import os
from moviepy.editor import VideoFileClip
def open_file():
file_path = filedialog.askopenfilename()
print("Selected file:", file_path)
#file_label.config(text="Selected file: " + file_path)
convert_to_mp3(file_path)
def convert_to_mp3(file_path):
if file_path:
video = VideoFileClip(file_path)
mp3_file_path = os.path.splitext(file_path)[0] + ".mp3"
video.audio.write_audiofile(mp3_file_path)
print("File converted to MP3:", mp3_file_path)
status_label.config(text="File is Converted")
save_button = tk.Button(root, text="Save File", command=lambda: save_file(mp3_file_path))
save_button.pack(pady=10)
def save_file(mp3_file_path):
save_path = filedialog.asksaveasfilename(defaultextension=".mp3", filetypes=[("MP3 Files", "*.mp3")])
if save_path:
os.rename(mp3_file_path, save_path)
status_label.config(text="File is Saved")
root = tk.Tk()
root.title("Video File Selector")
button = tk.Button(root, text="Select Video File", command=open_file)
button.pack(pady=20)
file_label = tk.Label(root, text="")
file_label.pack()
status_label = tk.Label(root, text="")
status_label.pack()
root.mainloop()
视频增强器代码:
import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog
def process_video():
file_path = filedialog.askopenfilename(title="Select a Video", filetypes=[("Video files", "*.mp4;*.avi")])
if file_path:
cap = cv2.VideoCapture(file_path)
# Get video properties
width = int(cap.get(3))
height = int(cap.get(4))
fps = int(cap.get(5))
# Create VideoWriter object to save the processed video
save_path = filedialog.asksaveasfilename(defaultextension=".avi", filetypes=[("Video files", "*.avi")])
if not save_path:
return
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(save_path, fourcc, fps, (width, height))
while True:
ret, frame = cap.read()
if not ret:
break
# Sharpening using addWeighted()
sharpened = cv2.addWeighted(frame, 7.5, cv2.GaussianBlur(frame, (7, 7), 2), -6.5, 0)
# Apply bilateral blur
bilateral_blur = cv2.bilateralFilter(sharpened, 9, 75, 75)
# Display the original, sharpened, and blurred video frames
cv2.imshow("Original Video", frame)
cv2.imshow("Sharpened Video", sharpened)
cv2.imshow("Blurred Video", bilateral_blur)
# Write the processed frame to the output video
out.write(bilateral_blur)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
# Enable Save button
save_button.config(state=tk.NORMAL)
# Store the processed video path in the global variable for saving
global processed_video_path
processed_video_path = save_path
def save_video():
save_path = filedialog.asksaveasfilename(defaultextension=".avi", filetypes=[("Video files", "*.avi")])
if save_path and processed_video_path:
# Copy the processed video file to the user-specified location
import shutil
shutil.copyfile(processed_video_path, save_path)
print(f"Processed video saved to {save_path}")
# Create the main application window
app = tk.Tk()
app.title("Video Processing App")
# Create and pack a button to trigger video processing
process_button = tk.Button(app, text="Process Video", command=process_video)
process_button.pack(pady=20)
# Create and pack a button to save the processed video (initially disabled)
save_button = tk.Button(app, text="Save Video", command=save_video, state=tk.DISABLED)
save_button.pack(pady=20)
# Run the Tkinter main loop
app.mainloop()
答: 暂无答案
评论