Python:从函数中获取选项?

问题描述 投票:0回答:3

我正在使用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
3个回答
0
投票

这有效,但不确定它是你想要的。

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

0
投票

问题是为什么建议您首先学习类并使用它们来编程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))

0
投票

在方法中添加global语句:

def choice(self,option):
   global foo
   foo = option
© www.soinside.com 2019 - 2024. All rights reserved.