0

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()
chrisHG
  • 80
  • 1
  • 2
  • 18

3 Answers3

1

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.

acw1668
  • 40,144
  • 5
  • 22
  • 34
  • oof thats embarrassing, that did the trick i'll accept the answer in 6 minutes since theres a timer for whatever reason – chrisHG Dec 08 '20 at 03:38
1

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...
Paul Brennan
  • 2,638
  • 4
  • 19
  • 26
  • Normally you shouldn't use `bind` with the button. The `command` attribute works better because it will be triggered both by the mouse and via the keyboard. – Bryan Oakley Dec 08 '20 at 05:11
1

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

Bhavyadeep Yadav
  • 819
  • 8
  • 25