-1

I am trying to import another file to be executed when clicking a button. So I have:

from tkinter import *
import file

window = Tk()
button = Button(window, text='GO', command=file.function())
button.grid(column=1, row=1)

This executes the file before the window is initialized. I also tried:

from file import function
button = Button(window, text='GO', command=function())

but it does the same thing. And neither of them are executed when clicking the button. How do you import files or functions but only executing them when the button is clicked? I am using python 3.5. Thank you

StevenH
  • 169
  • 1
  • 9

1 Answers1

2

You should do command=file.function instead of command=file.function().

The second one will call the function at the start of the program. In the first case, the function will be called when the button is clicked.

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • The button works now, but the file is still executed when imported? – StevenH Mar 03 '17 at 14:03
  • Make sure you don't call the function anywhere else in the file. Also, make sure that you do not call the function in the `file.py` itself, unless inside `if __name__ == "__main__":`. By doing `import file`, all the code from `file.py` is executed, except in the `if` I mentioned. I suggest you to search more about that. – Rok Povsic Mar 03 '17 at 14:05
  • Perfect, thank you – StevenH Mar 03 '17 at 14:10