1

I'd like to make checkbuttons from the lines in my txt file via path, and then want to get the value of the checkbuttons. In the 2021-03-27.txt

1. Python
2. C++

and then, if 1.Python is checked, I need to append 1. Python complete in 2021-03-27.txt

But I have no idea how I match the lines and variables of checkbuttons. How do I solve?

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()
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

Here is your solution

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()

You need to declare tk.IntVar() in chkvar instead of simple variable as tkinter updates IntVar on checkbox selection. Then read the chkvar and compare it and keep on writing information in the text as desired. Feel free to ask me in case of any question.

Usama Tariq
  • 169
  • 5
  • Thank you so much Barmar. It works and you solved my problem that I've been thinking for two days. Thank you again. – user15498167 Mar 28 '21 at 11:04
  • I have one more question. in txt file, I want to stop adding lists when meeting white space line. but the code in below read all lines including white space. Did I use 'break; wrong? for line in lines: if not line: break hw_lists.append(line) chkvar.append(IntVar()) f_open.close() – user15498167 Mar 28 '21 at 12:19
  • You can check in for line in lines by using if, when you find line == whitespace break the loop. – Usama Tariq Mar 28 '21 at 13:13