Tkinter 实例没有属性

Tkinter Instance has no attributes

我在使用 Tkinter 在音频播放器中播放音频的无辜愿望中遇到错误。错误是:

Traceback (most recent call last):
  File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 43, in   
<module>
    app = GUI(playerobj)
  File "C:\Users\Mudassar\workspace\Player\main_gui.py", line 10, in   
__init__
    self.create_button_frame()
AttributeError: GUI instance has no attribute 'create_button_frame'

我的代码 main_gui.py 是:

from Tkinter import *
import tkFileDialog
import player

class GUI:
    def __init__(self, player):
        self.player = player
        player.parent = player
        self.root = Tk()
        self.create_button_frame()
        self.create_bottom_frame()
        self.root.mainloop()

def create_button_frame(self):
    buttonframe = Frame(self.root)
    self.playicon = PhotoImage(file='../icons/play.gif')
    self.stopicon = PhotoImage(file='../icons/stop.gif')
    self.playbtn=Button(buttonframe, text ='play', image=self.playicon,   
    borderwidth=0, command=self.toggle_play_pause)

    self.playbtn.image = self.playicon
    self.playbtn.grid(row=3, column=3)
    buttonframe.grid(row=1, pady=4, padx=5)

def create_bottom_frame(self):
    bottomframe = Frame(self.root)
    add_fileicon = PhotoImage(file='../icons/add_file.gif')
    add_filebtn = Button(bottomframe, image=add_fileicon, borderwidth=0, 
    text='Add File', command = self.add_file)

    add_filebtn.image = add_fileicon
    add_filebtn.grid(row=2, column=1)
    bottomframe.grid(row=2, sticky='w', padx=5)

def toggle_play_pause(self):
    if self.playbtn['text'] == 'play':
        self.playbtn.config(text='stop', image=self.stopicon)
        self.player.start_play_thread()
    elif self.playbtn['text'] == 'stop':
        self.playbtn.config(text = 'play', image=self.playicon)
        self.player.pause()
def add_file(self):
    tfile = tkFileDialog.askopenfilename(filetypes = [('All supported',  
    '.mp3 .wav .ogg'), ('All files', '*.*')])
    self.currentTrack = tfile 

if __name__=='__main__':
    playerobj = player.Player()
    app = GUI(playerobj)

我的播放器按钮在另一个中的功能(因为它们与错误无关)是:

import pyglet
from threading import Thread 

class Player():
    parent = None
    def play_media(self):
        try:
            self.myplayer=pyglet.media.Player()
            self.source = pyglet.media.load(self.parent.currentTrack)
            self.myplayer.queue(self.source)
            self.myplayer.queue(self.source)
            self.myplayer.play()
            pyglet.app.run()
        except:
            pass

     def start_play_thread(self):
         player_thread = Thread(target=self.play_media)
         player_thread.start()
     def pause(self):
         try:
             self.myplayer.pause()
             self.paused = True
        except: pass

请帮忙。

看来你的问题是缩进。您的 create_button_frame() 函数不是 class GUI 的属性,它是一个全局函数。将参数 self 的所有函数向右缩进四个空格。然后它们将成为您的 class GUI 的方法。