简体   繁体   中英

Choosing file by clicking on a button [Python 2.7.6]

I'm trying to create a simple button that allows me to choose files such as text doc/pictures(jpg/png). I tried searching for answers here but didn't had any luck. I'm using Tkinter for my GUI interface.

This are my codes so far.

from Tkinter import *
root = Tk()
root.title("Hashing Tool")
root.geometry("600x300")

frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
button = Button(frame, text="Choose File", fg="black")
button.pack( side = BOTTOM)

from tkFileDialog import askopenfilename
filename = askopenfilename() 
print(filename)
root.mainloop()

Currently, you ask for a file as soon as the program starts. You have to put that part of the code into a callback function and pass that to the button's command parameter.

def getfile():
    filename = askopenfilename() 
    print(filename)

button = Button(frame, text="Choose File", fg="black", command=getfile)

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