In tkinter, python, I'm creating an info like text editor that uses StringVar() to display a file, also, with the use of entry and a button, I created a delete button, which deletes a certain line in a file. The problem I have is that the file does not delete the specified line and it does not update to show the file's contents. Here's my code:
from tkinter import *
root = Tk()
root.title("text")
root.geometry("700x700")
file = open(r"info.txt", "r")
lines = file.readlines()
file.close()
strd = StringVar()
def updatestr():
fileread = open(r"info.txt", "r")
lines2 = fileread.readlines()
strd.set("{}".format(lines2))
root.after(1, updatestr)
fileread.close()
updatestr()
lads = Label(root, textvariable=strd)
lads.pack()
blank = Label(root, text="")
blank.pack()
blank = Label(root, text="")
blank.pack()
blank = Label(root, text="")
blank.pack()
entry = Entry(root)
entry.configure(width=9)
entry.pack()
def DeleteEntry():
global file
file = open(r"info.txt", "w")
global lines
for line in lines:
if line!="{}".format(entry.get())+"\n":
file.write(line)
file.close()
confent = Button(root, text="Delete", command=DeleteEntry)
confent.configure(width=7)
confent.pack()
Not sure why this is happening, so I'd appreciate some help :)
Thanks
Related
I was making a simple flashcard tkinter application and I've encountered a problem such that when I manage the subjects, only every second item is added to the file.
For example, say I went to the manage subject page and I wanted to add the subjects: subject1, subject2, subject3, subject4, ... subjectN.
The only subjects that would add to the file are the subjects with the odd endings, is there a fix for this?
The code responsible for this:
#subjects window
def managesubjectsF():
def addF():
f = open ('subjectlist.txt', 'a')
f.write(addsubjectE.get() + '\n')
f.close()
addsubjectE.delete('0', 'end')
subjectPage = Tk()
subjectPage.title('Add subject')
subjectPage.resizable(False, False)
subjectPage.configure(background = 'light blue')
subjectPage.geometry('260x70')
addsubjectE = Entry(subjectPage, width=23, font=('bold', 14))
addsubjectE.grid(column=1, row=1)
addS = Button(subjectPage, text='Add', font=('bold', 15), command = addF)
addS.grid(column=1, row=2, sticky = N)
Minimal example of implementation:
#modules
from tkinter import *
import os.path
#implementations
count=0
subjectlist = []
#main window details
root = Tk()
root.geometry('225x350')
#list of available subjects
choice = Listbox(root, font = ('bold', 15))
choice.grid(column=1, row=2)
if os.path.exists('./subjectlist.txt') == True:
with open('subjectlist.txt', 'r') as f:
for line in f:
count += 1
f.close()
f = open('subjectlist.txt', 'r')
for i in range(count):
choice.insert(END, (f.readline().strip()))
subjectlist.append(f.readline().strip())
f.close()
else:
f = open('subjectlist.txt', 'w')
f.close()
#subjects window
def managesubjectsF():
def addF():
f = open ('subjectlist.txt', 'a')
f.write(addsubjectE.get() + '\n')
f.close()
addsubjectE.delete('0', 'end')
subjectPage = Toplevel()
subjectPage.geometry('260x70')
addsubjectE = Entry(subjectPage, width=23, font=('bold', 14))
addsubjectE.grid(column=1, row=1)
addS = Button(subjectPage, text='Add', font=('bold', 15), command = addF)
addS.grid(column=1, row=2, sticky = N)
#buttons
addsubjectsB = Button(root, text = 'Manage subjects', font = ('bold', 15), command = managesubjectsF)
addsubjectsB.grid(column=1, row=3, sticky = N)
root.mainloop()
(moving comment to answer)
You are calling readline twice which is moving the file pointer and skipping subjects.
for i in range(count):
choice.insert(END, (f.readline().strip()))
subjectlist.append(f.readline().strip()) # reading next line
Try reading the value once then storing in both lists:
for i in range(count):
s = f.readline().strip() # read once
choice.insert(END, (s))
subjectlist.append(s)
I have been trying to learn tkinter and have created something that post the results of a bunch of functions, and in the terminal the string formats works, but in the gui the string format does not work at all. I am super confused on why?
The code is below:
from tkinter import *
import ForFeesCovered
root = Tk()
root.title("Staff Fee Calculator")
root.geometry("375x400")
myLabel = Label(root,
text="Staff Fee Calculator")
e = Entry(root,
width=50,
borderwidth=5)
def output():
input_file = e.get()
f = ForFeesCovered.readfile(input_file)
file = ForFeesCovered.readfile(input_file)
staff = ForFeesCovered.getnamesofstaff(f)
staff.sort(reverse=False)
dic = ForFeesCovered.sort_dic(staff)
line_skip = 1
for lines in file:
line = lines.strip().split(",")
if line_skip != 1:
total = float("
{:.2f}".format(ForFeesCovered.getfeesforline(line)))
name = ForFeesCovered.get_name_of_staff(line, staff)
dic = ForFeesCovered.populating_dic(dic, name, total)
else:
line_skip += 1
string_dic = ""
result_file = open("result.txt", "w+")
for key in dic:
result_file.write("{} : {}\n".format(key, dic[key]))
string_dic = string_dic + "{:30} : {:>30}\n".format(key,
dic[key])
print(string_dic)
result_file.close()
output_dic = Label(root, text=string_dic, justify=LEFT)
output_dic.grid(row=2, column=0, pady=20)
submit = Button(root, text="Submit", command=output)
myLabel.grid(row=0, column=0)
e.grid(row=1, column=0,)
submit.grid(row=1, column=2)
root.mainloop()
The terminal is using a fixed-width font, the GUI is using a variable-width font.
If you are trying to line things up with spaces, you will need to used a fixed-width font.
I want to create a python GUI with one user input which will be inserted to an excel sheet whenever the user Enters insert button, and another button called e.g Show words, which will read all the words which are inserted into the excel sheet, any ideas how to do that ?
the excel sheet shoud be like this
and the user interface should be something simple like this
some code that I created for GUI but its for text file not excel
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
print("\n".join(content_list))
with open("help.txt", "a") as f:
for item in content_list:
f.write("%s\n" % item)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=1)
root.mainloop() ```
sorry if its silly question but this will be my first python GUI program
You can create GUI using python tkinter, you can also create input fields using this library and accept the entered value. After this you can simple use python csv library to insert a record into sheet.
You can find more information about tkinter Here
Use this code to read data from test.txt (use your txt file) file, insert data into file also as you asked it will also check if same data exist. You can view the data by clicking on view data button.
from tkinter import *
root = Tk()
root.geometry("700x700")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0)
def printSomething():
with open('help.txt') as f:
r = f.read()
label = Label(root, text=r)
label.grid()
def checkdata():
with open('help.txt') as f:
r = f.read()
return r.split("\n")
def writetofile():
exist_data = checkdata()
content_list = [ivn.get(), ivn2.get()]
with open("help.txt", "a") as f:
for item in content_list:
if item in exist_data:
msg = "Already exist "+item
label = Label(root, text=msg)
label.grid()
elif not item in exist_data:
f.write("%s\n" % item)
applyButton = Button(root, text="Add Data", command=writetofile)
applyButton.grid(row=2, column=1)
veiwButton = Button(root, text='View Data', command=printSomething)
veiwButton.grid(row=3, column=1)
root.mainloop()
Note: There are multiple ways to achieve this, one of them is this one.
I made a program with a List and this List is included in the Combobox. I want to write the List into a file in order to read the List again later, even after a restart of the program.
I tried this:
import tkinter as tk
from tkinter import ttk
import pickle
# window
win = tk.Tk()
win.title("menu")
List = []
newList = []
with open('data.txt', 'wb') as f:
pickle.dump(List, f)
with open('data.txt', 'rb') as f:
newList = pickle.load(f)
# button click event
def clickMe():
List.append(name.get())
numberChosen.configure(values=List)
# text box entry
ttk.Label(win, text="Eingabe:").grid(column=0, row=0)
name = tk.StringVar()
nameEntered = ttk.Entry(win, width=12, textvariable=name)
nameEntered.grid(column=0, row=1)
# button
action = ttk.Button(win, text="Enter", command=clickMe)
action.grid(column=2, row=1)
# drop down menu
ttk.Label(win, text="Auswahl:").grid(column=1, row=0)
number = tk.StringVar()
numberChosen = ttk.Combobox(win, width=12)
numberChosen['values'] = [List]
numberChosen.grid(column=1, row=1)
win.mainloop()
You just need to save the list to the file after mainloop, and load it at the start of the program.
with open('data.txt', 'rb') as file:
data = pickle.load(file)
...
win.mainloop()
with open('data.txt', 'wb') as file:
pickle.dump(data, file)
This will load the list at the start, and save it after the tk window closes.
What I need is to make the view orders button to get the text from the Customer.txt file and set it inside a textfield i made.
#make order,cancel,view
from tkinter import *
import tkinter.messagebox
root = Tk()
file = open("Customer.txt", "w")
def textW():
outFile = open("Customer.txt", "wt")
def CancelOrder():
outFile=open("Customer.txt", "w")
outFile.write("")
tkinter.messagebox.showinfo("Cancel Order", "Your order has been canceled")
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
#tViewOrder.set(test)
print (test)
#test.set(tViewOrder)
#outFile.close()
def MakeOrder():
outFile=open("Customer.txt", "w")
outFile.write("" + tMakeOrder.get())
tkinter.messagebox.showinfo("Make Order", "Order has been placed. Thank you!")
#Labels
lMakeOrder = Label(root, text="Make an order")
lViewOrder = Label(root, text="View Order")
#TextFields
tMakeOrder = Entry(root)
tViewOrder = Entry(root, state="disabled")
#Buttons
bMakeOrder = Button(root, text="Make order",bg="black",fg="green", command=MakeOrder)
bCancelOrder = Button(root, text="Cancel order",bg="black",fg="green", command=CancelOrder)
bViewOrder = Button(root, text="View orders",bg="black",fg="green", command=ViewOrder)
#Position
lMakeOrder.grid(row=0)
lViewOrder.grid(row=1)
tMakeOrder.grid(row=0, column=2)
tViewOrder.grid(row=1, column=2)
bMakeOrder.grid(row=4)
bViewOrder.grid(row=4, column=2)
bCancelOrder.grid(row=4, column=4)
#Window stuff
root.title("Sky is a shit name service - Customer")
root.geometry("300x300")
root.mainloop()
You can put text inside your Entry by calling insert function on it.
MyEntry.insert(POSITION, TEXT)
Oh and one more thing. You can't insert anything in the entry if it's disabled.
So here is your modified function:
def ViewOrder():
outFile = open('Customer.txt', 'r')
test = outFile.read()
tViewOrder['state'] = 'normal'
tViewOrder.delete(0, 'end') #Remove everything before
tViewOrder.insert(0, test)
tViewOrder['state'] = 'disabled'
outFile.close()