首页 > 解决方案 > 如何从 tkinter 中的函数获取组合框的值

问题描述

我创建了一个函数来在调用函数时显示一个新的组合框。但我无法获得所选组合框的值。

def drist(id):
    url = f"https://cdn-api.co-vin.in/api/v2/admin/location/districts/{id}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"}
    response = requests.request("GET", url, headers=headers)
    data = response.json()
    dist_name = [i['district_name'] for i in data['districts']]
    ds = tuple(dist_name)
    dris = StringVar()
    dist_ch = ttk.Combobox(window, width=27, textvariable=dris)
    dist_ch['values'] = ds  
    dist_ch.place(x=650, y=30) 
    dist_ch.bind("<<ComboboxSelected>>", clicked_dis)
    


def clicked_dis(event):
    print(dist_ch.get())

我怎样才能得到组合框的价值?

标签: pythontkinter

解决方案


您可以通过以下三种方法之一获取文本的值。

示例代码

from tkinter import *
from tkinter import ttk

def selection(event):
    # Three methods here all get the same value.
    print(event.widget.get())
    print(combo.get())
    print(combo_var.get())

root = Tk()

values = ['USA', 'CANADA', 'JAPAN', 'KOREA', 'CHINA']
combo_var = StringVar()

combo = ttk.Combobox(root, values=values, textvariable=combo_var)
combo.pack()
combo.bind("<<ComboboxSelected>>",  selection)

root.mainloop()

推荐阅读