chrisHG
chrisHG

Reputation: 80

Tkinter Button does not execute command

I'm trying to create a button that opens local files from a users machine. I have my buttons set up and the function to open files is pretty simple. When clicking the actual button, nothing actually happens. The intended result should be a box that opens that shows local files.

Here's my program so far:

from tkinter import *
import tkinter.filedialog

gui = Tk(className='musicAi')
gui.geometry("500x500")


def UploadAction(event=None):
    filename = filedialog.askopenfilename()
    print('Selected:', filename)

# create button
importMusicButton = Button(gui, text='Import Music', command = UploadAction, width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
linkAccountButton = Button(gui, text='Link Account', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
settingsButton = Button(gui, text='Settings', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
helpButton = Button(gui, text='Help', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
# add button to gui window
importMusicButton.pack()
linkAccountButton.pack()
settingsButton.pack()
helpButton.pack()


gui.mainloop()

Upvotes: 0

Views: 172

Answers (3)

smileycoolify
smileycoolify

Reputation: 21

Since you used the event object as parameters in Uploadfunction, use the bind method.

ImportMusicButton.bind(<"Button-1">, lambda:UploadAction())

In your UploadAction(event = None), remove the default value of an event parameter. Should be

def UploadAction(event):
    code goes here...

Upvotes: 1

Bhavyadeep Yadav
Bhavyadeep Yadav

Reputation: 831

I have perfect option for you.

Instead of using: import tkinter.filedialog you can use a better thing.

Use: from tkinter.filedialog import *

Then you can remove the filedialog from filename = filedialog.askopenfile().

Change it to: filename = askopenfile() :)

Upvotes: 1

acw1668
acw1668

Reputation: 46669

Since you import filedialog using import tkinter.filedialog, you need to use tkinter.filedialog.askopenfilename() to execute askopenfilename().

Change import tkinter.filedialog to from tkinter import filedialog or import tkinter.filedialog as filedialog.

Upvotes: 1

Related Questions