python 11 TK下拉列表及返回值
时间: 2024-05-16 10:15:48 浏览: 199
可以使用 tkinter 中的 Combobox 组件来创建下拉列表,并使用 get() 方法获取用户选择的值。
以下是一个简单的示例代码:
```python
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
# 创建下拉列表
values = ['apple', 'banana', 'orange']
selected_value = tk.StringVar()
combobox = ttk.Combobox(root, textvariable=selected_value, values=values)
combobox.pack()
# 获取用户选择的值
def get_selected_value():
value = selected_value.get()
print('Selected value:', value)
button = tk.Button(root, text='Get selected value', command=get_selected_value)
button.pack()
root.mainloop()
```
运行代码后,会弹出一个窗口,其中包含一个下拉列表和一个按钮。用户可以从列表中选择一个值,然后点击按钮来打印所选的值。
相关问题
tkinter下拉框单选并获取返回值
在Tkinter中,如果你想创建一个下拉框式的选择器,并且只能选择其中的一项作为单选,你可以使用`OptionMenu`组件。这里是一个简单的例子:
```python
import tkinter as tk
def get_selected_value():
# 获取当前选中的选项的索引
selected_index = option_menu.curselection()[0]
# 获取对应的选项值,假设我们有一个字典映射了选项和它们的值
selected_value = options[selected_index]
return selected_value
root = tk.Tk()
options = ["选项A", "选项B", "选项C"] # 可供选择的选项列表
selected_value = "" # 初始化返回值
# 创建下拉菜单
option_menu = tk.OptionMenu(root, tk.StringVar(), *options)
option_menu.pack() # 显示下拉框
# 绑定事件,当用户选择一个选项时触发get_selected_value函数
option_menu.config(command=get_selected_value)
root.mainloop()
```
在这个示例中,`tk.StringVar()`用于保存用户的选择,`*options`表示将`options`列表中的每个元素作为下拉框的一个选项。当你点击下拉框并选择一个项时,`command`属性指定的函数会被调用,返回所选值。
阅读全文
相关推荐












