Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to open a file in tkinter

trying to make a GUI with an 'open file' button. When I run the code shown below, the open file dialog opens straight away, and not when I press the button. Why? Is there a simple way to fix this that doesn't involve using classes? (I don't currently know anything about classes and am working on a time-pressured project)

from tkinter import *

interface = Tk()

def openfile():
    return filedialog.askopenfilename()

button = ttk.Button(interface, text = "Open", command = openfile())
button.grid(column = 1, row = 1)

interface.mainloop()
like image 456
Jake Levi Avatar asked Sep 30 '22 12:09

Jake Levi


1 Answers

The code is passing the return value of the openfile function call, not the function itself. Pass the function itself by removing trailing () which cause a call.

from tkinter import *
from tkinter import ttk
from tkinter import filedialog

interface = Tk()

def openfile():
    return filedialog.askopenfilename()

button = ttk.Button(interface, text="Open", command=openfile)  # <------
button.grid(column=1, row=1)

interface.mainloop()
like image 191
falsetru Avatar answered Oct 02 '22 14:10

falsetru