-2

I can't figure out why the function that I've called auto runs when I run the script, without pressing the button.

import tkinter
from tkinter import filedialog


root = tkinter.Tk ()
root.title("fool")
root.geometry("300x300")
br = tkinter.Button(root, text ="Carica File", command = filedialog.askopenfile(mode="r"))
br.pack()
the302storm
  • 49
  • 1
  • 6

1 Answers1

0

Right now, you're passing the result of the call

filedialog.askopenfile(mode="r")

to the command parameter. To be able to get this result, the function is executed and you're seeing the dialog right away. What you probably want to do is just provide the name of a function to call when the button is pressed, so you could define one as

def foo():
    filedialog.askopenfile(mode="r")

and use

command = foo

In the Button call. What you're doing in your code above corresponds to command = foo() instead (which executes the function), and not command = foo.

If you want to do everything in the same line, and not define an extra function, you could also use a lambda and write:

command = lambda: filedialog.askopenfile(mode="r")
brm
  • 3,706
  • 1
  • 14
  • 14