Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 Tkinter open webbrowser on click

Tags:

python

tkinter

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.

like image 603
phales15 Avatar asked Feb 21 '23 22:02

phales15


2 Answers

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:

like image 86
joaquin Avatar answered Mar 05 '23 17:03

joaquin


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()
like image 32
gary Avatar answered Mar 05 '23 16:03

gary