这是我的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()
这将显示以下屏幕:
如果选中一个复选框并单击,则显示 CMD 的输出如下:
接下来,我尝试将输出保存到 .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/