Python 2.7 Tkinter open webbrowser on click
Asked Answered
E

3

5
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.

Erich answered 5/1, 2012 at 12:40 Comment(0)
C
5

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:

Catnip answered 5/1, 2012 at 12:57 Comment(0)
C
3

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()
Cosmography answered 5/1, 2012 at 13:23 Comment(0)
G
0

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.

Giaimo answered 15/7, 2023 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.