Tkinter 将从 optionMenu 中选择的选项带入变量以供进一步使用

Tkinter bringing chosen option from optionMenu into a variable for further use

在 "tkinter" 中创建下拉菜单时,如下所示:

options = ['0',
           '1',
           '2',
           '3',
           '4']

option = tk.OptionMenu(menu, var, *options)

var.set('Select number')

我想确切地知道如何将用户选择的整数转换为我以后可以使用的变量。

Question: how I can take the integer that the user has chosen

您将 options 定义为 str 的列表,因此在您的代码 var 中,所选选项将分配给给定的 textvariable。要从 str 中获取 integer,请执行以下操作:

option_int = int(var.get())

工作示例,如何获取所选 OptionMenu 项的 index

import tkinter as tk

class myOptionMenu(tk.OptionMenu):
    def __init__(self, parent):
        self.item = tk.StringVar()
        self.item.set("Select option")  # default value
        self.index = None
        self.options = ['0. Option', '1. Option', '2. Option', '3. Option']

        super().__init__(parent, self.item, *self.options, command=self.command)
        self.pack()

    def command(self, v):
        # Loop 'options' to find the matching 'item', return the index
        self.index = [i for i, s in enumerate(self.options) if s == self.item.get()][0]
        print("def option({}), variable.get()=>{}, index:{}".format(v, self.item.get(), self.index))
        # >>> def option(2. Option), variable.get()=>2. Option, index:2

root = tk.Tk()

option = myOptionMenu(root)

root.mainloop()

Usage in the main loop:

if option.item.get() == '2. Option':
    print("Option {} is selected.".format(option.item.get()))

if option.index == 2:
    print("Option {} is selected.".format(option.index))

测试 Python:3.5.3 - TkVersion: 8.6