简体   繁体   English

Tkinter Optionmenu StringVar.get() 返回空白

[英]Tkinter Optionmenu StringVar.get() returning blank

I am creating a Tkinter window with a 'for loop' so it can self-adjust if later on, I decide to add more questions.我正在创建一个带有“for 循环”的 Tkinter 窗口,以便以后可以自行调整,我决定添加更多问题。 My issue is that I can't save the inputted value on the optionmenu.我的问题是我无法在选项菜单上保存输入的值。 So far all I got was a list1 = ['', '', ''] while the Strg_var = [StringVar, StringVar, StringVar] and it prints only the blanks and the variables PY_numbers.到目前为止,我得到的只是一个list1 = ['', '', '']Strg_var = [StringVar, StringVar, StringVar]并且它只打印空白和变量 PY_numbers。

import tkinter as tk
from tkinter import *

LARGE_FONT = ("Arial", 12)

window=Tk()

def _save():
    print(*list1, sep = ", ")
    print(*Strg_var, sep = ", ")

Questionlist = ["A. Is A true? :", "B. Is B true? :", "C. Is C true? :"]          
choices = ['-', 'Yes', 'No'] 
n = 0
Strg_var=[0]*len(Questionlist)
list1=[]
for n in range(len(Questionlist)): 
    Label(window, text=Questionlist[n], font = LARGE_FONT, background = "white").grid(row= n, column=0, columnspan=2, padx=10, pady = 10, sticky="W")
    a = tk.StringVar(window)
    OptionMenu(window, a, choices[0], *choices).grid(row = n, column=2, padx=10, sticky="WE")
    list1.append(a.get())

tk.Button(window, text="Save", command = _save,width=18).grid(row=16, column=0, padx=10, pady=15, sticky="W")

window.mainloop()

Can someone help me to sort this out on how to save the optionmenu user selections into a list or any other way?有人可以帮助我解决如何将选项菜单用户选择保存到列表或任何其他方式的问题吗?

You can make a list of StringVar (Do Initialise them, I haven't done that in my code).您可以制作一个StringVar列表(请初始化它们,我的代码中没有这样做)。 Every time an option is selected the corresponding item will change.每次选择一个选项时,相应的项目都会改变。 So I would do it like this.所以我会这样做。

import tkinter as tk

LARGE_FONT = ("Arial", 12)

window=tk.Tk()

def _save():
    print(list(map(lambda x: x.get(), a)))

Questionlist = ["A. Is A true? :", "B. Is B true? :", "C. Is C true? :"]          
choices = ['-', 'Yes', 'No']
a = [tk.StringVar(window) for i in range(len(Questionlist))]
n = 0
for n in range(len(Questionlist)): 
    tk.Label(window, text=Questionlist[n], font = LARGE_FONT, background = "white").grid(row= n, column=0, columnspan=2, padx=10, pady = 10, sticky="W")
    Strg_var = tk.StringVar(window)
    tk.OptionMenu(window, a[n], *choices).grid(row = n, column=2, padx=10, sticky="WE")

tk.Button(window, text="Save", command = _save,width=18).grid(row=16, column=0, padx=10, pady=15, sticky="W")

window.mainloop()

在此处输入图片说明

Output:输出:

['No', '-', 'Yes']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM