【问题标题】:Add images to decorate Tk window in python?在python中添加图像来装饰Tk窗口?
【发布时间】:2021-07-25 18:21:23
【问题描述】:

我是上周开始的python新用户。我正在创建一个音乐库或音乐播放器作为我的学校作业之一,只要它在同一个文件中,用户就可以单击箭头跳到下一首歌曲。然而,一个问题! GUI 看起来很糟糕而且超级无聊。我今天有 2 个问题:

  1. 如何更改整个布局的背景图像并在背景中使用我自己的图像进行 Photoshop 处理以增加趣味性?最后我希望做的是在广阔的空间中播放一个视频,这是一个首选的视频,这样他们在听他们选择的歌曲时至少可以看到一些不错的东西。

这就是愚蠢的东西:

代码如下:

#     GUI     #
import tkinter as tk
from tkinter import *
from tkinter import filedialog


#     AUDIO   #
from pygame import mixer

#     DIRECTORY NAVIGATION   #
from os import walk

#     EXCEPTION HANDLER   #
import pygame

#     VOLUME CONTROL   #
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume, ISimpleAudioVolume
from ctypes import cast, POINTER
# YOU MIGHT NEED TO PIP INSTALL THESE
# IF THOSE DONT WORK TRY
# py -m pip install [library]
# pip install pycaw
# pip install comtypes
# pip install psutil



class MP:
    
    def __init__(self, win):
        # Create Tkinter window
        win.geometry('600x300')
        win.title('Jared AIT Music Player')
        win.resizable(0, 0)
 

        # StringVar to change button text later
        self.play_restart = tk.StringVar()
        self.pause_resume = tk.StringVar()
        self.play_restart.set('Play')
        self.pause_resume.set('Pause')

        # The buttons and their positions
        load_button = Button(win, text='Load', width=10, font=("Arial", 10), command=self.load)
        load_button.place(x=50,y=250, anchor='center')

        play_button = Button(win, textvariable=self.play_restart, width=10, font=("Arial", 10), command=self.play)
        play_button.place(x=150,y=250, anchor='center')

        pause_button = Button(win, textvariable=self.pause_resume, width=10, font=("Arial", 10), command=self.pause)
        pause_button.place(x=250,y=250, anchor='center')

        stop_button = Button(win, text="Stop", width=10, font=("Arial", 10), command=self.stop)
        stop_button.place(x=350,y=250, anchor='center')

        next_button = Button(win ,text = '>>',  width = 10, font = ('Arial', 10), command = self.next)
        next_button.place(x=550,y=250, anchor='center')

        back_button = Button(win ,text = '<<',  width = 10, font = ('Arial', 10), command = self.back)
        back_button.place(x=450,y=250, anchor='center')

        #SLIDERS
        volume_slider = Scale(win, from_=100, to=0, orient=VERTICAL, command=self.volume, length=125)
        volume_slider.grid(row=0, column=1)



 
 

        self.music_file = False
        self.playing_state = False

        
    def volume(self,volume_level):
        #       THIS INITIALISES THE VOLUME CONTROL     #
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(
        IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))

        #       THIS SETS THE VOLUME    #
        volume.SetMasterVolumeLevelScalar(int(volume_level)/100, None)

        

    def load(self):
        self.music_file = filedialog.askopenfilename(initialdir="/AIT Python 1/Assets", title="Select a song", filetypes=(("wav files", "*.wav"),("all files", "*.*"),("mp3 files", "*.mp3")))
        print("Loaded:", self.music_file)
        self.play_restart.set('Play')

    


    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
            self.playing_state = False
            self.play_restart.set('Restart')
            self.pause_resume.set('Pause')

    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state = True
            self.pause_resume.set('Resume')
        else:
            mixer.music.unpause()
            self.playing_state = False
            self.pause_resume.set('Pause')

    def stop(self):
        mixer.music.stop()

    ########################################################################################################       
    def next(self):
        self.file_path = (self.music_file.rsplit("/",1))[0].replace("/","\\")
        if "/" in self.music_file:
            self.file_name = self.music_file.rsplit("/",1)[1]
        else:
            self.file_name = self.music_file

        self.filenames = next(walk(self.file_path), (None, None, []))[2]
        self.file_count = 0

        for i in self.filenames:
            if i == self.file_name:
                break
            self.file_count += 1

        self.next_file = self.file_count + 1
        self.directory_limit = len(self.filenames)
        if self.next_file == self.directory_limit:
            self.next_file = 0
        self.music_file = self.file_path + "/" + self.filenames[self.next_file]
        self.file_count = 0
        mixer.init()
        try:
            mixer.music.load(self.music_file)
        except pygame.error as message:
            while True:
                self.next_file += 1
                if self.next_file == self.directory_limit:
                    self.next_file = 0
                self.music_file = self.file_path + "/" + self.filenames[self.next_file]
                self.file_extension = self.music_file.rsplit(".",1)[1]
                if (".wav") or (".mp3") in self.file_extension:
                    mixer.music.load(self.music_file)
                    break
        
        mixer.music.play()



    def back(self):
        self.file_path = (self.music_file.rsplit("/",1))[0].replace("/","\\")
        if "/" in self.music_file:
            self.file_name = self.music_file.rsplit("/",1)[1]
        else:
            self.file_name = self.music_file

        self.filenames = next(walk(self.file_path), (None, None, []))[2]
        self.file_count = 0

        for i in self.filenames:
            if i == self.file_name:
                break
            self.file_count += 1

        self.back_file = self.file_count - 1
        self.directory_limit = len(self.filenames)
        if self.back_file == self.directory_limit:
            self.back_file = 0
        self.music_file = self.file_path + "/" + self.filenames[self.back_file]
        self.file_count = 0
        mixer.init()
        try:
            mixer.music.load(self.music_file)
        except pygame.error as message:
            while True:
                self.back_file += 1
                if self.back_file == self.directory_limit:
                    self.back_file = 0
                self.music_file = self.file_path + "/" + self.filenames[self.back_file]
                self.file_extension = self.music_file.rsplit(".",1)[1]
                if (".wav") or (".mp3") in self.file_extension:
                    mixer.music.load(self.music_file)
                    break
        
        mixer.music.play()







        ########################################################################################################      




root = tk.Tk()
MP(root)
root.mainloop()
  1. 如何制作一个音频清理器,让用户可以转到歌曲的不同时间间隔?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    我不太确定音频清理器,我的 tkinter 接口从来不需要音频,所以我无法就此提供建议。对于图像,您可能会发现在 __init__ 方法中添加类似这样的内容很有帮助:

    # import the background image
    self.background = Image.open('path/to/image')
    self.background = self.background.resize((x_dim, y_dim), Image.ANTIALIAS)
    self.background = ImageTk.PhotoImage(self.background)
    
    # create background
    win.create_image(x_pos, y_pos, image=self.background)
    

    对于您需要的导入:

    # 'pip install pillow' if needed
    from PIL import ImageTk, Image
    

    您当然需要定义x_dimy_dim 以使您的图像适合。对于x_posy_pos,您提供的坐标将是 Tkinter 放置背景图像的中心点。

    希望对您有所帮助!

    【讨论】:

    • 如果您愿意,当然可以添加单独的方法来添加图像。
    【解决方案2】:

    首先恭喜你这么快就进入了 Python!

    第一个问题:

    您可以使用 tkinter 中提供的 PhotoImage 类在 tkinter 中导入图像:

    bg = PhotoImage(file="image_path")

    导入图像后,您可以使用标签将图像放置到 GUI 上:

    backgroundLabel = Label(win, image=bg)
    backgroundLabel.place(x=0, y=0)
    

    我个人从未在 tkinter 中做过视频播放器,但我找到了 this pypi module

    我不知道你的第二个问题,抱歉。

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 2017-07-31
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 2019-06-09
      • 2022-10-12
      • 1970-01-01
      • 2011-12-29
      相关资源
      最近更新 更多