user2837162
user2837162

Reputation:

Creating a GUI with executable button

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())

Upvotes: 0

Views: 332

Answers (1)

abarnert
abarnert

Reputation: 366073

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()

Upvotes: 2

Related Questions