gpt4 book ai didi

python - Tkinter Optionmenu StringVar.get() 返回空白

转载 作者:行者123 更新时间:2023-12-01 08:46:34 26 4
gpt4 key购买 nike

我正在创建一个带有“for 循环”的 Tkinter 窗口,以便在以后我决定添加更多问题时它可以进行 self 调整。我的问题是我无法保存选项菜单上输入的值。到目前为止,我得到的只是 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()

有人可以帮我解决如何将选项菜单用户选择保存到列表或任何其他方式吗?

最佳答案

您可以创建一个StringVar列表(初始化它们,我没有在我的代码中这样做)。每次选择一个选项时,相应的项目都会发生变化。所以我会这样做。

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

enter image description here

输出:

['否'、'-'、'是']

关于python - Tkinter Optionmenu StringVar.get() 返回空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com