Python: Getting option from function?

不羁的心 提交于 2019-12-11 14:03:52

问题


I'm working with Tkinter in Python and am using OptionMenu and want to get the selection the user makes.

ex1 = StringVar(root)
ex1.set("Pick Option")
box = OptionMenu(root, "one","two","three", command=self.choice)

def choice(self,option):
   return choice

It work when I just do:

print choice

But I though I could somehow return it and then store it in a variable. For example, at the start of the code I made:

global foo
foo = ""

and then tried:

def choice(self,option):
   foo = option
   return foo

But this didn't work. Does anyone know where I am going wrong? Thanks.


回答1:


This works, but not sure it is what you wanted.

from Tkinter import StringVar
from Tkinter import OptionMenu
from Tkinter import Tk
from Tkinter import Button
from Tkinter import mainloop

root = Tk()
ex1 = StringVar(root)
ex1.set("Pick Option")
option = OptionMenu(root, ex1, "one", "two", "three")
option.pack()


def choice():
    chosen = ex1.get()
    print 'chosen {}'.format(chosen)
    # set and hold using StringVar
    ex1.set(chosen)
    root.quit()
    # return chosen


button = Button(root, text="Please choose", command=choice)
button.pack()
mainloop()
# acess the value from StringVar ex1.get
print 'The final chosen value {}'.format(ex1.get())



回答2:


The question is an example of why it is suggested that you learn classes first and use them to program a GUI https://www.tutorialspoint.com/python3/python_classes_objects.htm

import sys
if 3 == sys.version_info[0]:  ## 3.X is default if dual system
    import tkinter as tk     ## Python 3.x
else:
    import Tkinter as tk     ## Python 2.x

class StoreAVariable():
    def __init__(self, root):
        self.root=root
        self.ex1 = tk.StringVar(root)
        self.ex1.set("Pick Option")
        option = tk.OptionMenu(root, self.ex1, "one", "two", "three")
        option.pack()

        tk.Button(self.root, text="Please choose", command=self.choice).pack()

    def choice(self):
        self.chosen = self.ex1.get()

        ## the rest has nothing to do with storing a value
        print('chosen {}'.format(self.chosen))
        self.ex1.set(self.chosen)
        self.root.quit()
        # return chosen


root = tk.Tk()
RV=StoreAVariable(root)
root.mainloop()

print('-'*50)
print('After tkinter exits')
print('The final chosen value={}'.format(RV.chosen))



回答3:


Add global statement inside the method:

def choice(self,option):
   global foo
   foo = option


来源:https://stackoverflow.com/questions/48958535/python-getting-option-from-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!