首页 > 解决方案 > 如何在 TK Inter 中使用图像和按钮?

问题描述

我是 Python 的新用户,我正在努力弄清楚如何在 TK Inter 中使用图像作为按钮。我目前正在为一个学校作业做一个小型项目,在那里我制作了一个小型音乐库,我希望它看起来不错。但是,由于缺少颜色,我的项目目前非常无聊。

如何从 youtube 合并此代码:

from tkinter import *

root = Tk()
root.title('hello')
root.geometry('400x400')

login_btn = PhotoImage(file='pc.png')

img_label = Label(image = login_btn)
img_label.pack(pady=20)

mainloop()

进入这个:

#     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)
        win.iconbitmap('icon.ico')




        


        








        

        # 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


        
#IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE



#IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE IMAGE


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

我正在寻找替换按钮:“加载”、“播放”、“暂停”、“停止”、“下一步”和“返回”。与图像。有人有想法吗?

标签: pythontkinter

解决方案


下面是我最近实现可以作为图像加载的按钮的方式。有些功能与我的需求有关,因此您可能不需要全部。

# Method from my app class

def add_button(self, message, alias, x, y, function, args="", image_path="", subsample=0):
    if image_path != "":
        photo = PhotoImage(file = image_path)
        photo_image = photo.subsample(subsample, subsample)
        self.images[alias] = photo_image
        btn = Button(self.window, text=message, command=function, image=photo_image)
    else:
        btn = (Button(self.window, text=message, command=function)
        if args == "" else (Button(self.window, text=message, command=lambda:function(args))))
    btn.place(y=y, x=x)
    self.buttons[alias] = btn

#Add button to the app (I usually call in the init)
[...]
app.add_button(MY_MESSAGE, ALIAS_TO_STORE_THE_BUTTON, x, y, MYFUNCTION, "", "PATH_TO_IMAGE", 8)

推荐阅读