Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

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

when creating a drop-down menu in "tkinter" like this:

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

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

var.set('Select number')

I want to know exactly how I can take the integer that the user has chosen and turn it into a variable that I can use later on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

You define options as a list of str, therefore the chosen option are assigned to the given textvariable, in your code var. To get a integer from the str do:

option_int = int(var.get())

Working example, how to get the index of a chosen OptionMenu item:

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))

Tested with Python:3.5.3 - TkVersion: 8.6


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...