python - 如何获取复选框值保存到文本文件中?

标签 python tkinter output

这是我的Python代码:

from tkinter import *
master = Tk()

def var_states():
   print("Option 1: %d\nOption 2: %d" % (var1.get(), var2.get()))

Label(master, text="Option").grid(row=0, sticky=W)
var1 = IntVar()
Checkbutton(master, text="Option 1", variable=var1).grid(row=1, sticky=W)
var2 = IntVar()
Checkbutton(master, text="Option 2", variable=var2).grid(row=2, sticky=W)
Button(master, text='Quit', command=master.quit).grid(row=3, sticky=W, pady=4)
Button(master, text='Show', command=var_states).grid(row=4, sticky=W, pady=4)




mainloop()

这将显示以下屏幕:

enter image description here

如果选中一个复选框并单击,则显示 CMD 的输出如下:

enter image description here

接下来,我尝试将输出保存到 .txt 文件中。这是我尝试过的:

f = open("output.txt", "w")
f.write(var_states())
f.close()

#open and read the file after the appending:
f = open("output.txt", "r")
print(f.read())

但这会返回以下错误:TypeError: write() argument must be str, not None

但是如果我将这个 f.write(var_states()) 转换为 f.write(str(var_states()))

它完成了这项工作,但将 None 打印到 .txt 文件中。

如何在 CMD 输出时将复选框值保存到 .txt 文件中?

最佳答案

您的 var_states 函数实际上不会返回任何内容。它只是打印到控制台。将其更改为:

def var_states():
   res = "Option 1: %d\nOption 2: %d" % (var1.get(), var2.get())
   print(res)
   return res
<小时/>

此外,您应该使用 with,而不是手动打开关闭文件:

with open("output.txt", "w") as f:
  f.write(var_states())

#open and read the file after the appending:
with open("output.txt", "r") as f:
  print(f.read())

文件在 with block 末尾自动关闭

关于python - 如何获取复选框值保存到文本文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57902588/

相关文章:

python - 如何为 ttk.Combobox 设置浮雕?

c - 如果在 main 中定义,为什么程序只提供输出(我该如何更改它)?

java - 通过 Ant 任务运行 javac 时如何查看编译器输出?

python - 使用Python的docx库,如何对表格进行缩进?

ubuntu上的python全gui屏幕

python - 在带有 Python 的 Tk 中,我如何指定一个框架或 Canvas 以随我的窗口调整大小?

c - termios.h 如何使用位掩码来确定终端应该是什么模式?

python - 以特定格式提取 Excel 数据作为 python 文件的输入

python - PhantomJS 在 Selenium : WebDriverException with status code 127 上意外退出

python - 使用 Python 在 XML 中查找和替换值