gpt4 book ai didi

python - 默认为并选择 Tkinter 列表框中的第一项

转载 作者:太空狗 更新时间:2023-10-30 00:26:28 25 4
gpt4 key购买 nike

我想自动选择列表框中的第一项。通过选择第一项,我并不是说简单地默认第一项或将焦点设置在它上面。我已经通过执行 self.listbox.select_set(0) 实现了这一点。我还想选中默认项。换句话说,当我运行下面的代码时,我希望 print(value) 打印默认选择的值。如果从选项菜单中选择亚洲,日本应该自动打印到控制台。如果是非洲,尼日利亚应该打印,欧洲应该打印德国。

关于如何实现这一点有什么建议吗?谢谢。

from tkinter import *
from tkinter import ttk
import tkinter.messagebox

class App:
def __init__(self):
self.master = Tk()
self.di = {'Asia': ['Japan', 'China', 'Malaysia', 'India', 'Korea',
'Vietnam', 'Laos', 'Thailand', 'Singapore',
'Indonesia', 'Taiwan'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia', 'Ghana',
'Congo', 'Senegal', 'Guinea', 'Mali', 'Cameroun',
'Benin', 'Tanzania', 'South Africa', 'Zimbabwe']}
self.variable_a = StringVar()
self.frame_optionmenu = ttk.Frame(self.master)
self.frame_optionmenu.pack()
options = sorted(self.di.keys())
self.optionmenu = ttk.OptionMenu(self.frame_optionmenu, self.variable_a, options[0], *options)

self.variable_a.set('Asia')
self.optionmenu.pack()
self.btn = ttk.Button(self.master, text="Submit", width=8, command=self.submit)
self.btn.pack()

self.frame_listbox = ttk.Frame(self.master)

self.frame_listbox.pack(side=RIGHT, fill=Y)
self.scrollbar = Scrollbar(self.frame_listbox )
self.scrollbar.pack(side=RIGHT, fill=Y)
self.listbox = Listbox(self.frame_listbox, selectmode=SINGLE, yscrollcommand=self.scrollbar.set)
self.variable_a.trace('w', self.updateoptions)

self.scrollbar.config(command=self.listbox.yview)
self.listbox.pack()

#Populate listbox
for each in self.di[self.variable_a.get()]:
self.listbox.insert(END, each)
self.listbox.select_set(0) #This only sets focus on the first item.
self.listbox.bind("<<ListboxSelect>>", self.OnSelect)

self.master.mainloop()

def updateoptions(self, *args):
#countries = self.di[self.variable_a.get()]
self.listbox.delete(0, 'end')
for each in self.di[self.variable_a.get()]:
self.listbox.insert(END, each)
self.listbox.select_set(0) #This only sets focus on the first item.
self.listbox.pack()

def submit(self, *args):
var = self.variable_a.get()
if messagebox.askokcancel("Selection", "Confirm selection: " + var):
print(var)

def OnSelect(self, event):
widget = event.widget
value = widget.get(widget.curselection()[0])
print(value)

App()

运行 Python 3.4.1

最佳答案

最简单的解决方案是生成 <<ListboxSelect>>在您更改选择的同时发生事件:

def updateoptions(self, *args):
...
self.listbox.select_set(0) #This only sets focus on the first item.
self.listbox.event_generate("<<ListboxSelect>>")
...

关于python - 默认为并选择 Tkinter 列表框中的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25415888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com