-1

The problem I am experiencing is that when I want to create a button which is supposed to do a certain action on being pressed, the action happens right away when the program starts. In clearer terms, I have an os.system("sudo python /home/pi/module2.py") in a function. This is what the function might look like (oh, yeah, I imported os, and tkinter as tk):

def __init__(self, parent, controller):
    button = tk.Button(self,
        text="Addition",
        command=os.system("sudo python /home/pi/module2.py")

What happens with this is that the os.system function is run before anything else starts, because it is in a function at the top of the file, and I call on the functions at the bottom of the file. So, even though the os.system is in a function, it still runs when it shouldn't. Can someone help?

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Welcome to StackOverflow! I boiled down your question to the core of the problem. This way it has a better chance of helping others because they might have the same problem as you but would never find it with your lengthy introduction and misleading title. Please don't be upset :) It's just meant to improve StackOverflow. – Alfe Oct 10 '16 at 00:37

1 Answers1

0

You need to pass a function to command= which will do what you want. In your solution you pass to command= the result of calling such a function, hence it is performed prematurely.

A typical way of coding this would be:

def __init__(self, parent, controller):

    def call_module2(*args, **kwargs):  # accept all possible arguments
        os.system("sudo python /home/pi/module2.py")

    button = tk.Button(self,
        text="Addition",
        command=call_module2)

Or, if you prefer to use anonymous functions via lambda:

def __init__(self, parent, controller):
    button = tk.Button(self,
        text="Addition",
        command=lambda *args, **kwargs:
            os.system("sudo python /home/pi/module2.py"))
Alfe
  • 56,346
  • 20
  • 107
  • 159