我正在尝试根据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 个单选按钮中 是、否、不适用。只能选择一个。
- 接下来,当按下按钮时
save
..它会在docx
中创建一个表,选项row 0
与所选值"是","否"和"不适用"一起向下追加。
举个例子:
Options Yes No N/a
Option 1 *
Option 2 *
Option 3 *
我的问题:
我可以简单地按save
,它将文件保存为test.docx
。
现在,我正在尝试弄清楚如何将文件保存为Failed.docx
仅当所有选项中的一个或多个选项选择了no
值时,才会创建Failed.docx
。
作为下面的示例,这将另存为Test.docx
,因为没有一个选项选择了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 loop
输出:
False
True
False
但是,如果它检测到False
并True
则将保存两个文件。我完全困惑从这里去哪里..
问题:只有在选择了
no
值的所有options
中if one or more
,才会创建'Failed.docx'
。
这可以改写为:
if any option has NO
您已经根据条件value == NO
构建了Boolean
list
,例如[False, True, False]
- 内置 - 任何
任意(可迭代(
如果可迭代对象的任何元素为 true,则返回 True。如果可迭代对象为空,则返回 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')
输出:
[2, 0, 2]
test.docx
[2, 1, 2]
Failed.docx
尝试以下操作:
for x in cells[2].text:
if "*" in x:
print("Failed.docx")
elif "*" not in x:
print("Test.docx")
这将检查no
行内是否有任何"*"
,如果存在,则另存为Failed.docx
(如果不是另存为Test.docx