【问题标题】:Python: Getting option from function?Python:从函数中获取选项?
【发布时间】:2018-02-24 01:44:21
【问题描述】:

我正在使用 Python 中的 Tkinter,并且正在使用 OptionMenu 并希望获得用户所做的选择。

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

def choice(self,option):
   return choice

当我这样做时它会起作用:

print choice

但我虽然可以以某种方式返回它,然后将它存储在一个变量中。例如,在我制作的代码的开头:

global foo
foo = ""

然后尝试:

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

但这没有用。有谁知道我哪里出错了?谢谢。

【问题讨论】:

    标签: python user-interface tkinter scope


    【解决方案1】:

    这可行,但不确定它是否是您想要的。

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

    【讨论】:

    • 感谢您的回复。我知道这是在做什么,但是当调用“return selected”时,如果您知道我的意思,我希望将其分配给该函数范围之外的变量?
    • 你是对的,返回不起作用,选择的值必须使用ex1.setex1.get()方法从StringVar访问
    【解决方案2】:

    这个问题是一个例子,说明为什么建议你先学习类并使用它们来编写 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】:

      在方法添加global声明:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        相关资源
        最近更新 更多