【问题标题】:return multiple values from list box tkinter python从列表框tkinter python返回多个值
【发布时间】:2022-01-05 11:24:40
【问题描述】:

我正在尝试从列表框中返回选择值。

首先,我有一个组合框,用户需要在其中选择区域(A、B、C....)
选择区域后,小部件上会出现一个列表框,用户需要选择其他选项。当我尝试从列表框中选择值时,它什么也不打印,空列表。

如何返回其他选项?

  • 这是代码的一部分

     def sheetChosenLabel(event):
    
        area = combo_sheet.get()  # Get the selection from the user
        area_listbox = Listbox(frame3, background=PowderBlue, font=("ariel", 9), relief="sunken")
        area_listbox.place(relx=0.09, rely=0.4, height=100, width=100)
        area_listbox.configure(selectmode=MULTIPLE)
    
        for item in Sheets[area]:
            area_listbox.insert(END, item)
    
        results = []
        for index in area_listbox.curselection():
            results.append(area_listbox.get(index))
        print results
    

GUI

【问题讨论】:

  • area_listbox 被创建之后,您将获得选定的项目,然后您将一无所获,因为没有选择任何内容。
  • 你用的是python 2.x吗?
  • 是的,我使用的是 2.7
  • @acw1668 那我该怎么办?
  • 创建一个按钮,并在点击按钮时在回调中获取选中的项目。

标签: python tkinter listbox listboxitem


【解决方案1】:

由于您在创建area_listbox 之后立即获得了选定的项目,因此您将一无所获。

您可以改为在由按钮触发的函数中执行此操作。还可以在 sheetChosenLabel() 之外创建列表框并在函数内更新其内容。

以下是基于您发布的代码的示例:

import tkinter as tk
from tkinter import ttk

# sample data
Sheets = {
    'A': (f'A{i}' for i in range(1, 10)),
    'B': (f'B{i}' for i in range(1, 20)),
    'C': (f'C{i}' for i in range(1, 8)),
}


def sheetChosenLabel(event):
    # update listbox based on selected area
    area = combo_sheet.get()
    area_listbox.delete(0, tk.END)
    for item in Sheets[area]:
        area_listbox.insert(tk.END, item)


def check_result():
    # get and show the selected items in listbox
    result = [area_listbox.get(i) for i in area_listbox.curselection()]
    print(result)


root = tk.Tk()

frame3 = tk.Frame(root)
frame3.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)

combo_sheet = ttk.Combobox(frame3, values=list(Sheets.keys()), state='readonly')
combo_sheet.pack(padx=10, pady=5)
combo_sheet.bind('<<ComboboxSelected>>', sheetChosenLabel)

area_listbox = tk.Listbox(frame3, bg='PowderBlue', font='Arial 9', relief='sunken', selectmode=tk.MULTIPLE)
area_listbox.pack(padx=10, pady=5)

check_button = tk.Button(frame3, text='Check', command=check_result)
check_button.pack(padx=10, pady=5)

root.mainloop()

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多