我可以为 tkinter 中的每个组合框值使用一个元组吗?

问题描述 投票:0回答:1

我在组合框中的每个选项都有数据元组,但我无法对其进行索引或提取字符串数字,即最后的第 2 列。在使用 get() 提取值后,我可以创建列表来分隔值,但是有没有办法分别从元组中获取每个值?可能不是,但我在文档中找不到它。

这是代码:

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define  Tuple
data = [('Value A', 'First', '1.5'), ('Value B', 'Next', '4.5'), ('Value C', 'Last', '5.5')]


# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= data
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

selected_value = cb.get()

# Create a button to clear the selected combobox text value
button = Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()

我想获取与选择匹配的浮点值,即值 A 为 1.5。数字始终是每个元组的最后一个,我认为这将允许使用 get() 方法进行一些索引,但我不能让它发挥作用。

python tkinter ttk ttkcombobox
1个回答
0
投票

好吧,您可以将一个函数绑定到组合框选择事件,然后从所选元组中提取相应的浮点值。

您可以通过创建

handle_selection
函数来处理组合框选择来做到这一点

def handle_selection(event):
    selected_index = cb.current()  # Get the index of the selected item
    selected_tuple = data[selected_index]  # Get the selected tuple
    selected_float = float(selected_tuple[-1])  # Extract the float value from the tuple
    print(selected_float)  # Print the extracted float value

然后将组合框值设置为每个元组的第一个元素。您可以在创建组合框小部件时这样做:

cb['values'] = [item[0] for item in data]

创建组合框后,确保将handle_selection函数绑定到组合框选择事件

cb.bind("<<ComboboxSelected>>", handle_selection)
© www.soinside.com 2019 - 2024. All rights reserved.