如何在 python tkinter 中从 txt 文件创建多个复选框
How do I create multiple checkboxes from txt file in python tkinter
我想通过路径从我的 txt 文件中的行创建复选按钮,然后想要获取复选按钮的值。
在2021-03-27.txt
1. Python
2. C++
然后,如果选中 1.Python
,我需要在 2021-03-27.txt
中附加 1. Python complete
但我不知道如何匹配复选按钮的行和变量。我该如何解决?
path = "/Study/2021-03-27.txt"
f_open = open(path, "r")
lines = f_open.readlines()
hw_lists = []
chkvar = []
for line in lines:
hw_lists.append(line)
f_open.close()
chkvar_count = 0
for hw_list in hw_lists:
Checkbutton(root, text=hw_list, variable=chkvar[chkvar_count]).pack()
chkvar_count += 1
def resut_output():
for i in range(len(hw_lists)-1):
if chkvar == 1:
f_open = open(path, "a")
f_open.write(hw_lists[i]+"complete")
f_open.close()
Button(root, text="OK", command=resut_output).pack()
root.mainloop()
这是您的解决方案
import tkinter as tk
from tkinter import *
path = "2021-03-27.txt"
f_open = open(path, "r")
lines = f_open.readlines()
hw_lists = []
chkvar = []
root = tk.Tk()
for line in lines:
hw_lists.append(line)
chkvar.append(tk.IntVar())
f_open.close()
chkvar_count = 0
for hw_list in hw_lists:
print(chkvar_count)
Checkbutton(root, text=hw_list, variable=chkvar[chkvar_count]).pack()
chkvar_count += 1
def resut_output():
for i in range(len(hw_lists)):
if chkvar[i].get() == 1:
f_open = open(path, "a")
f_open.write('\n' + hw_lists[i].strip('\n') + " complete")
f_open.close()
Button(root, text="OK", command=resut_output).pack()
root.mainloop()
您需要在 chkvar 中声明 tk.IntVar() 而不是简单变量,因为 tkinter 在复选框选择时更新 IntVar。然后阅读 chkvar 并进行比较,并根据需要继续在文本中写入信息。有问题随时问我
我想通过路径从我的 txt 文件中的行创建复选按钮,然后想要获取复选按钮的值。
在2021-03-27.txt
1. Python
2. C++
然后,如果选中 1.Python
,我需要在 2021-03-27.txt
1. Python complete
但我不知道如何匹配复选按钮的行和变量。我该如何解决?
path = "/Study/2021-03-27.txt"
f_open = open(path, "r")
lines = f_open.readlines()
hw_lists = []
chkvar = []
for line in lines:
hw_lists.append(line)
f_open.close()
chkvar_count = 0
for hw_list in hw_lists:
Checkbutton(root, text=hw_list, variable=chkvar[chkvar_count]).pack()
chkvar_count += 1
def resut_output():
for i in range(len(hw_lists)-1):
if chkvar == 1:
f_open = open(path, "a")
f_open.write(hw_lists[i]+"complete")
f_open.close()
Button(root, text="OK", command=resut_output).pack()
root.mainloop()
这是您的解决方案
import tkinter as tk
from tkinter import *
path = "2021-03-27.txt"
f_open = open(path, "r")
lines = f_open.readlines()
hw_lists = []
chkvar = []
root = tk.Tk()
for line in lines:
hw_lists.append(line)
chkvar.append(tk.IntVar())
f_open.close()
chkvar_count = 0
for hw_list in hw_lists:
print(chkvar_count)
Checkbutton(root, text=hw_list, variable=chkvar[chkvar_count]).pack()
chkvar_count += 1
def resut_output():
for i in range(len(hw_lists)):
if chkvar[i].get() == 1:
f_open = open(path, "a")
f_open.write('\n' + hw_lists[i].strip('\n') + " complete")
f_open.close()
Button(root, text="OK", command=resut_output).pack()
root.mainloop()
您需要在 chkvar 中声明 tk.IntVar() 而不是简单变量,因为 tkinter 在复选框选择时更新 IntVar。然后阅读 chkvar 并进行比较,并根据需要继续在文本中写入信息。有问题随时问我