Tkinter:通过下拉菜单打开URL.需要从列表中指定Item



另一个我确信我有正确想法的谜题,但我似乎无法实现它。

我试着做一个下拉菜单,立即打开URL到列表的第一列但是我不确定我是否需要一个字典并从中调用它,我是否需要按列定义列表。

所以我弄清楚了如何从TreeView打开URL,但现在我弄清楚了如何从下拉菜单打开URL。在本例中,我希望{spec}仅由列表中的第一项(Pepperoni)填充。


QUICKJUMP_1 = [ 
["--", "--"],
["Pepperoni", "Pizza"],
]
def openGoogle():
_spec_ = QUICKJUMP_1
url = f'https://google.com/{_spec_}'
webbrowser.open(url)

quickjump = StringVar()
quickjump.set(QUICKJUMP_1[0])
spec = ttk.Combobox(root, width=30, textvariable=quickjump, state="") 
spec['values'] = [item[1] for item in QUICKJUMP_1]
spec.place(x=300, y=400)
spec.current(0)
spec.bind("<<ComboboxSelected>>", openGoogle)

编辑:

我更新了代码,因为它弄清楚了如何使它实际打开URL但就目前而言,它目前所做的只是打开列表的第一部分无论列表的哪一部分spec= QUICKJUMP"指向[1]= item 2。

所以我需要告诉它从下拉框中选取并且只选取第一部分

由于给出的代码不是一个工作代码,我将写下一个例子,你可以希望从中找出它:

from tkinter import *
from tkinter import ttk
import webbrowser
root = Tk()
base_url = 'www.google.com/{}'
options = ['--','Peperoni Pizza']
def open_url(e): # e.widget is the widget that triggers the event, here, combobox
if e.widget.get() != options[0]: # If the value is not '--'
value = e.widget.get()
just_the_flavour = value.split(' ')[0] # This will split the text 'Peperoni Pizza' into two items in a list
# It does this where there is ' ', ie, a blank space, so the list will be ['Peperoni','Pizza']
# Then we take just the first item from it use [0]

url = base_url.format(just_the_flavour)
webbrowser.open(url)

combobox = ttk.Combobox(root,values=options)
combobox.pack()
combobox.current(0) # Set the first value to the first in the list
combobox.bind('<<ComboboxSelected>>',open_url) # Bind to the function
root.mainloop()

我已经在注释中解释了它,以便在旅途中理解它。

最新更新