简体   繁体   中英

Python function TypeError upon TkInter button click command

I have the following code:

import mp3play
try:

    from Tkinter import *
except ImportError:

    from tkinter import *

root = Tk()

def playMusic(root):
    filename = r'D:\My Documents\School Work\A2 Computing\Project\Westerado.mp3'
    mp3 = mp3play.load(filename)
    mp3.play()

# Declaring the buttons
button1 = Button(text="Play", fg="Black", height=1, width=7, command= playMusic)

and some more which is irrelevant to this error, however when I run the program the GUI wil show up as normal, except that when I click button1 I get the following error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\Python2.7\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
TypeError: playMusic() takes exactly 1 argument (0 given)

I have not done much work with Python functions and button commands and therefore am uncertain of what has gone wrong although I do believe that the function playMusic 's parameter(s) are incorrect.

What do I need to change here in order to get this working? I know that if I take out the def playMusic(root): altogether, then when I run to code the music will play as it should. But it is the button click command that is incorrect.

EDIT -

I have switched to def play_music():, now I do not get any error when I click the button. Instead, the program button will look like it has frozen being clicked down as if it is trying to do something but nothing will come of it.

I was playing around with the code to try and get something to work and I found that if I made this:

filename = r'D:\My Documents\School Work\A2 Computing\Project\Westerado.mp3'
mp3 = mp3play.load(filename)

global; and then within the function just have this:

def play_music():
    mp3.play()

then when I go to click the button "play" it works perfectly fine!

Not sure why this works and the other way did not! But right now I'm not complaining.

So overall it looks like:

filename = r'D:\My Documents\School Work\A2 Computing\Project\Westerado.mp3'
mp3 = mp3play.load(filename)

def play_music():
    mp3.play()

# Declaring the buttons
button1 = Button(text="Play", fg="Black", height=1, width=7, command=play_music)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM