phales15
phales15

Reputation: 465

Python 2.7 Tkinter open webbrowser on click

from Tkinter import *
import webbrowser

root = Tk()
frame = Frame(root)
frame.pack()

url = 'http://www.sampleurl.com'

def OpenUrl(url):
    webbrowser.open_new(url)

button = Button(frame, text="CLICK", command=OpenUrl(url))

button.pack()
root.mainloop()

My goal is to open a URL when I click the button in the GUI widget. However, I am not sure how to do this.

Python opens two new windows when I run the script without clicking anything. Additionally, nothing happens when I click the button.

Upvotes: 5

Views: 15915

Answers (3)

ko100
ko100

Reputation: 120

I know this is 11 years old but it's the first Google result for me, so I'll post my solution:

ttk.Button(frame, text="Help", command=lambda: webbrowser.open_new("https://example.com")).pack(anchor="w")

No function is needed; it's almost like writing an anchor tag in HTML.

Upvotes: 0

gary
gary

Reputation: 4255

Alternatively, you don't have to pass the URL as an argument of the command. Obviously your OpenUrl method would be stuck opening that one URL in this case, but it would work.

from Tkinter import *
import webbrowser

url = 'http://www.sampleurl.com'

root = Tk()
frame = Frame(root)
frame.pack()

def OpenUrl():
    webbrowser.open_new(url)

button = Button(frame, text="CLICK", command=OpenUrl)

button.pack()
root.mainloop()

Upvotes: 3

joaquin
joaquin

Reputation: 85603

You should use

button = Button(root, text="CLCK", command=lambda aurl=url:OpenUrl(aurl))

this is the correct way of sending a callback when arguments are required.
From here:

A common beginner’s mistake is to call the callback function when constructing the widget. That is, instead of giving just the function’s name (e.g. “callback”), the programmer adds parentheses and argument values to the function:

If you do this, Python will call the callback function before creating the widget, and pass the function’s return value to Tkinter. Tkinter then attempts to convert the return value to a string, and tells Tk to call a function with that name when the button is activated. This is probably not what you wanted.

For simple cases like this, you can use a lambda expression as a link between Tkinter and the callback function:

Upvotes: 5

Related Questions