python - 如何从 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())
我怎样才能得到组合框的价值?
解决方案
您可以通过以下三种方法之一获取文本的值。
示例代码
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()
推荐阅读
- mongodb - MongoDB:计算所有文档中的第 90 个百分位
- angular - 我的应用程序没有在 Internet Explorer 和 Edge 中路由
- python-3.x - Docker 中的 python 脚本需要访问不同 Docker 映像中存在的 API 数据
- java - 从命令行运行 .jar 时出现 NetBeans 8.2 中指定的命令行参数
- c# - 时间间隔重叠但在第二天
- java - 正确答案按钮绿色
- python - 在调用另一个类函数的类函数中返回一个值
- android - 应用程序崩溃,但堆栈跟踪中没有应用程序特定代码
- php - httpd.conf 上的用户/组的 Apache 问题 - 权限
- android - 在 Android exoplayer 视频中显示登录的用户名