Tkinter实例没有属性

时间:2015-01-27 03:45:13

标签: python-2.7 tkinter

我对使用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

请帮忙。

1 个答案:

答案 0 :(得分:1)

好像你的问题是缩进。您的create_button_frame()函数不是类GUI的属性,它是一个全局函数。将参数self四个空格的所有函数缩进到右侧。然后它们将是您的类GUI的方法。