python - 如何根据从 tkinter 中选择的值保存 docx 文件?
问题描述
这是我的代码:
from tkinter import *
from docx import Document
root = Tk()
info = ["Option 1", "Option 2", "Option 3"]
vars = []
for idx,i in enumerate(info):
var = IntVar(value=0)
vars.append(var)
lblOption = Label(root,text=i)
btnYes = Radiobutton(root, text="Yes", variable=var, value=2)
btnNo = Radiobutton(root, text="No", variable=var, value=1)
btnNa = Radiobutton(root, 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)
def save():
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 = "*"
for x in cells[2].text:
if "*" in x:
print("Failed.docx")
elif "*" not in x:
print("Test.docx")
savebtn = Button(root, text = "Save", command = save).grid()
root.mainloop()
这是我之前的问题:链接
我已使用其中一个答案将其与我的问题结合起来。
我想要达到的目标:
如果no
已通过单选按钮选择了任何选项,则将文档保存为failed.docx
好像每个选项都已被选择而没有任何选项,no's
然后将文件另存为Test.docx
.
我的问题是:
为什么我的最后一个 for 循环和 if 语句不起作用。
当我选择 no 选项时,它会返回 Failed.docx。但是,如果没有no'
选择任何一个,它什么都不做?根本不运行 elif 语句。
解决方案
cells
在您的代码中,您通过在每次迭代中创建来逐行写入 docx 。单元格是包含单个选项的三个单选按钮值的行。假设您选择Yes
选项 3,单元格将包含 [* '' ''] 用于其迭代。
cells[0] = *
cells[1] = ''
cells[2] = ''
此外,当您尝试迭代时cells[1].text
,您正在尝试迭代一个空项目。这就是为什么它永远不会进入if-elif
语句,因为它永远不会进入 for 循环。
(不确定我是否设法清楚地解释了这一点,但如果您使用未选择的单选按钮或调试器的值,您可以清楚地看到发生了什么)
对于解决方案,由于您要检查单个列的所有值,因此可以使用table.column。
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 = "*"
cells[2].text = "not-selected"
cells[3].text = "not-selected"
elif val == 1: # checks if no
cells[2].text = "*"
cells[1].text = "not-selected"
cells[3].text = "not-selected"
elif val == 0: # checks if N/A
cells[3].text = "*"
cells[1].text = "not-selected"
cells[2].text = "not-selected"
fn = 'Test.docx'
for cell in table.columns[2].cells[1:4]: #column2 is No column, 1:4 excludes header cell
if cell.text == '*':
fn = 'Failed.docx'
break
print(fn)
推荐阅读
- javascript - Express Validator 5.3 - 如果第二个参数包含在给定数组中,则为必需参数
- c# - 尝试读取数据库 C# 错误
- javascript - C# Razor View 将 null 对象传递给 JavaScript
- intellij-idea - 清除 Intellij/pycharm 状态栏中的旧消息
- sql - 在 SQL Server 中乘以时间
- c - 在 Allegro 中创建弹丸轨迹
- sql - 我有一个不是 dbo 的默认架构,为什么该架构中的内容并不总是被使用?
- java - 使用 PDFMergerUtility 合并 PDF 而不会丢失标签
- dialogflow-es - dialogflow Webhookclient“request_”属性
- java - Spring Security 登录和注册