在Python中以编程方式在网页浏览器中打开URL

8 投票
2 回答
2600 浏览
提问于 2025-04-17 05:43

我有一个用tkinter写的脚本。我想知道有没有办法让它在你点击一个按钮时,打开一个网站。

from tkinter import *
app = Tk()
app.geometry("250x400")
app.title("Links")

def Link():
    ?

button1 = Button(app, text = "To a web site.", command = Link)
button1.pack()

app.mainloop()

2 个回答

1

使用webbrowser模块来打开一个URL。你可以查看相关的说明文档:https://docs.python.org/3/library/webbrowser.html

# You can use open 
from webbrowser import open
def link():
    open('https://www.youtube.com/')
# You can use open_new_tab
from webbrowser import open_new_tab
def link():
    open_new_tab('https://www.youtube.com/')
  
16

有一个模块可以做到这一点

import webbrowser

webbrowser.open("http://xkcd.com/353/")

撰写回答