0

Hi I am using Python27 on Window7 OS, i am trying to create a Tk GUI with button, when the button is press a file directory will appear. But the following code won't do anything. Did i miss out something?

import webbrowser
import Tkinter as Tk

def action(self):
    webbrowser.open ('C:\AgmPlots')

win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command= lambda: action())
1
  • 1
    A couple of side notes: lambda: action() does exactly the same thing as just passing action, except that it's more complicated, less readable, and slower. And you don't normally want to add a self parameter on a function; that's for methods in a class. Commented Oct 16, 2013 at 3:22

1 Answer 1

2

You've got three big problems.

First, you never start the GUI. You need something like win.mainloop() at the end to actually do anything.

Second, your button isn't actually laid out within the frame, so you won't see it. You need something like button.pack().

Finally, your command is a function that calls action(), with no arguments. But you've defined it to require a parameter. So, all that will happen when you click it is that Tk will log a traceback that looks like this:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "tkt.py", line 8, in <lambda>
    button = Tk.Button(master=frame, text='press', command= lambda: action())
TypeError: action() takes exactly 1 argument (0 given)

To fix that, either don't add the unnecessary self parameter to action (this is a function, not a method), or explicitly pass some dummy to match it in your lambda.

While we're at it, lambda: action() does exactly the same thing as action itself, except more verbose, harder to read, and slower. You should never use unescaped backslashes in non-raw string literals. And we might as well remove the stray spaces and PEP8-ify everything to make it consistent.

So, putting it all together:

import webbrowser
import Tkinter as Tk

def action():
    webbrowser.open(r'C:\AgmPlots')

win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)
button.pack()

win.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.