首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从多个tkinter选项菜单中获取值?

如何从多个tkinter选项菜单中获取值?
EN

Stack Overflow用户
提问于 2021-10-18 13:27:50
回答 1查看 648关注 0票数 0

你好,我需要创建一个窗口,有5个不同的下拉菜单,我需要保存5个给出的答案。我设法用5种不同的下拉菜单创建了窗口。但是,当我运行代码时,只保存了最后的答案。我如何检索所有的5个选项?谢谢

代码语言:javascript
复制
    # Import the tkinter module
import tkinter
  
# Create the default window
root = tkinter.Tk()
root.title("Thruster types")
#root.geometry('700x500')
  
# Create the list of options
options_list = 'Tunnel', 'Azimuth', 'Pod', 'Shaft Line', 'Cycloid'
  

  
#Create an empty list that I will fill with my inputs
Thruster=[None]*5
# Create the optionmenu widget and passing 
# the options_list and value_inside to it.
for i in range (0, 5, 1):
    # Variable to keep track of the option selected in OptionMenu
    value_inside = tkinter.StringVar(root)
     # Set the default value of the variable
    value_inside.set("Thruster"+str(i+1))   
    question_menu = tkinter.OptionMenu(root, value_inside, *options_list)
    question_menu.pack()

    
def print_answers():

    print(value_inside.get()) #Placing the inputs into the list Thruster
    return None
  
  
# Submit button
# Whenever we click the submit button, our submitted
# option is printed ---Testing purpose
submit_button = tkinter.Button(root, text='Submit', command=print_answers)
submit_button.pack()

root.mainloop()
print(Thruster)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-18 13:38:54

为循环中创建的每个StringVar创建一个列表来存储OptionMenu。然后,对列表中的每个值调用.get()来获取该值。

如下所示:

代码语言:javascript
复制
    # Import the tkinter module
import tkinter
  
# Create the default window
root = tkinter.Tk()
root.title("Thruster types")
#root.geometry('700x500')
  
# Create the list of options
options_list = 'Tunnel', 'Azimuth', 'Pod', 'Shaft Line', 'Cycloid'
  

  
#Create an empty list that I will fill with my inputs
Thruster=[None]*5

# list of all StringVars for each OptionMenu
values = []

# Create the optionmenu widget and passing 
# the options_list and value_inside to it.
for i in range (0, 5, 1):
    # Variable to keep track of the option selected in OptionMenu
    value_inside = tkinter.StringVar(root)
     # Set the default value of the variable
    value_inside.set("Thruster"+str(i+1))   
    question_menu = tkinter.OptionMenu(root, value_inside, *options_list)
    question_menu.pack()
    values.append(value_inside)

    
def print_answers():
    for val in values:
        print(val.get()) #Placing the inputs into the list Thruster
    return None
  
  
# Submit button
# Whenever we click the submit button, our submitted
# option is printed ---Testing purpose
submit_button = tkinter.Button(root, text='Submit', command=print_answers)
submit_button.pack()

root.mainloop()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69616973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档