【问题标题】:Tkinter combobox loop again. Getting the resultsTkinter 组合框再次循环。得到结果
【发布时间】:2021-10-01 17:24:27
【问题描述】:

我通过循环列表创建了一组组合框,然后 使用 dict 键作为项目 em 组合列表。问题:我无法将结果返回到“结果”列表。所有组合框同时更改。我研究过有关该主题的其他帖子,但我无法理解解决方案中涉及的概念。 总而言之:代码生成了 3 个组合框,但它们一起更改,我无法附加结果。

提前感谢您的帮助:

#------------------------代码

from tkinter import 
from tkinter import ttk
win = Tk()
win.geometry('400x600')
win.title('combobox')


result =[] #--> the new list with results of comboboxes

opts = StringVar()

anyFruits =['any_grape', 'any_tomato', 'any_banana'] 
#--> list just to generate the loop 


fruits = {'specialgrape':'specialgrape', 'specialtomato':'specialtomato','specialbanana':'specialbanana'}
#--> dictonary to generate drop down options menu (key of dict)

for index, fruit in enumerate(anyFruits):

    mycombo = ttk.Combobox(win, 
                           values= (list(fruits.keys())),textvariable=opts)

    mycombo.bind('<<ComboboxSelected>>', lambda event, index=index: fruit_callBack(index, event))
    
    mycombo.pack()


    
def fruit_callBack(index, event):
    
    for opts in mycombo:
        
        result.append(opts)



def print_():        
    print(result)


bt = Button(win,command= print_)

bt.pack()

win.mainloop()

【问题讨论】:

  • 解决的第一个问题:单独填写组合框 opts 必须放在循环内
  • 您预计会发生什么。它们同时发生变化,因为它们都有相同的textvariable。

标签: list loops dictionary tkinter combobox


【解决方案1】:

因为所有Combobox 都具有相同的textvariable,所以值会一起变化。因此,改变一个,将迫使其他人保持相同的价值。无论如何,你也附加错了,你不需要传入index,只需传递组合框本身并在其中附加值即可:

for index, fruit in enumerate(anyFruits):
    mycombo = ttk.Combobox(win,values=list(fruits.keys()))
    mycombo.bind('<<ComboboxSelected>>',lambda e,cmb=mycombo: fruit_callBack(e,cmb))   
    mycombo.pack()
   
def fruit_callBack(event,cmb):
    result.append(cmb.get())

【讨论】:

  • 谢谢您的启发。
  • 嘿!你真的解决了问题。非常感谢。周末愉快。
  • 也祝你周末愉快
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
相关资源
最近更新 更多