Newbie question, problem with functions

R

Rickard Karlsson

I have wrote this little program, that is supposed to execute eg. the
Linux ls command when you press a button. Te problem is that all the
commands are run automaticly and they won't run when I press the
associated button. Wath am I do wrong?

from Tkinter import *
import os

class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()

b1 = Button(frame, text = "ls", command = self.execute('ls'))
b2 = Button(frame, text = "ls -alh", command = self.execute('ls
-alh'))
b3 = Button(frame, text = "pwd", command = self.execute('pwd'))

b1.grid(column=0, row=1)
b2.grid(column=0, row=2)
b3.grid(column=0, row=3)

def execute(self,com):
os.system(com)

root = Tk()

app = App(root)

root.mainloop()
 
P

Peter Otten

Rickard said:
I have wrote this little program, that is supposed to execute eg. the
Linux ls command when you press a button. Te problem is that all the
commands are run automaticly and they won't run when I press the
associated button. Wath am I do wrong?
[...]
b1 = Button(frame, text = "ls", command = self.execute('ls'))
b2 = Button(frame, text = "ls -alh", command = self.execute('ls
-alh'))
b3 = Button(frame, text = "pwd", command = self.execute('pwd'))
[...]

You are in fact passing the result of self.execute(...), i. e. None, instead
of the method. Do

b3 = Button(frame, text="pwd", command=lambda: self.execute('pwd'))

instead or define wrapper methods like so:

def executeLs(self):
self.execute("ls")

and assign them to the buttons without a trailing (), e. g.:

b1 = Button(frame, text="ls", command=self.executeLs)

Peter
 
R

Rickard Karlsson

You are in fact passing the result of self.execute(...), i. e. None, instead
of the method. Do

b3 = Button(frame, text="pwd", command=lambda: self.execute('pwd'))


Thank you so much, it works fine now.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top