将tkinter与Python结合使用,是否可以在列表框中包含多个URL?

时间:2019-06-19 21:24:48

标签: python-3.x tkinter

我是tkinter的新手,我正在尝试构建一个应用程序,该应用程序允许用户单击出现在窗口中的列表中的不同URL并提示进入相应的网站。

在下面的示例中,我展示了一个简单的测试用例,我希望用户能够通过单击语音“ Google新闻”或“ Yahoo新闻”下方的URL来访问Google新闻。语音“雅虎新闻”。

from tkinter import *
import webbrowser

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

list_of_items = ['Google news',
                 'https://news.google.com/',
                 'Yahoo news',
                 'https://news.yahoo.com/']
root = Tk()
lb = Listbox(root)
for item in list_of_items:
    lb.insert(END, item)
    if 'https://' in item:
        lb.bind("<Button-1>", weblink(item))
lb.pack()
root.mainloop()

问题在于,运行脚本后,它将自动打开网页,而无需单击根窗口中出现的URL。即使单击URL,也不会发生任何事情。

我正在Windows上使用Python 3.6。

谢谢!

1 个答案:

答案 0 :(得分:1)

即使该功能像您想的那样工作,您仍将按钮绑定到整个列表框,而不是绑定到一行。因此,您的函数需要确定单击了哪个元素以及是否为url。实际上,这是唯一的方法。我将推荐事件ListboxSelect而不是Button-1。

from tkinter import *
import webbrowser

def weblink(*args):
    index = lb.curselection()[0]
    item = lb.get(index)
    if 'https://' in item:
        webbrowser.open_new(item)

list_of_items = ['Google news',
                 'https://news.google.com/',
                 'Yahoo news',
                 'https://news.yahoo.com/']
root = Tk()
lb = Listbox(root)
lb.bind('<<ListboxSelect>>', weblink)
for item in list_of_items:
    lb.insert(END, item)
lb.pack()
root.mainloop()
相关问题