我正在尝试根据 if 语句保存文档。
我在这里创建单选按钮:
info = ["Option 1", "Option 2", "Option 3"]
vars = []
for idx,i in enumerate(info):
var = IntVar(value=0)
vars.append(var)
lblOption = Label(main,text=i)
btnYes = Radiobutton(main, text="Yes", variable=var, value=2)
btnNo = Radiobutton(main, text="No", variable=var, value=1)
btnNa = Radiobutton(main, text="N/A", variable=var,value=0)
lblOption.grid(column=4,row=idx, sticky = W)
btnYes.grid(column=1,row=idx)
btnNo.grid(column=2,row=idx)
btnNa.grid(column=3,row=idx)
这里我正在创建一个文档
document = Document()
#add table
table = document.add_table(1, 4)
#style table
table.style = 'Table Grid'
#populate header row
heading_cells = table.rows[0].cells
heading_cells[0].text = "Options"
heading_cells[1].text = "Yes"
heading_cells[2].text = "No"
heading_cells[3].text = "N/a"
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
elif val == 1: # checks if no
cells[2].text = "*"
elif val == 0: # checks if N/A
cells[3].text = "*"
#save doc
document.save("test.docx")
幕后工作:
- 在 3 个单选按钮 Yes、No、N/a.. 中只能选择一个。
- 接下来,当按下按钮
save时,它会在docx中创建一个表格,Options在第0行中附加到选定的是、否和 N/a 的值。
举个例子:
Options Yes No N/a
Option 1 *
Option 2 *
Option 3 *
我的问题:
我只需按 save 即可将文件保存为 test.docx。
现在,我想知道如何将文件保存为 Failed.docx
Failed.docx 仅当所有选项中的一个或多个选择了 no 值时才会创建。
作为下面的示例,这将被保存为 Test.docx,因为没有一个 Option 具有选择的 no 值:
Options Yes No N/a
Option 1 *
Option 2 *
Option 3 *
下面的示例,这将被保存为 Failed.docx,因为已为左侧选项之一选择了 no 选项。
举个例子:
Options Yes No N/a
Option 1 *
Option 2 *
Option 3 *
这是我到目前为止尝试过的:
for x in cells[2].text:
if "*" in x:
print("True")
else:
print("False")
这会检测 cell[2] 中的 *(这是链接到 No 值的第 2 行)。
如果选择了“否”值,它会打印出 true 但也会打印出 false
举个例子:
Options Yes No N/a
Option 1 *
Option 2 *
Option 3 *
for 循环 的输出:
False
True
False
但是如果它检测到 False 和 True 两个文件都将被保存。我完全不知道从这里去哪里..
请您参考如下方法:
Question: The
'Failed.docx'will only be createdif one or moreout of all theoptionshas anovalue selected.
这可以改写为:
if any option has NO
您已经根据条件 value == NO 构建了一个 list Boolean,
像 [False, True, False]
- Built-in - any
any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False.
YES = 2; NO = 1; NA = 0
print(vars)
if any([v.get() == NO for v in vars]):
print('Failed.docx')
else:
print('test.docx')
Output:
[2, 0, 2]
test.docx
[2, 1, 2]
Failed.docx
