Arithmetic Summation in the file operations using Python Tkinter - python

please help me run arithmetic summation in the file operations using Python Tkinter
input should be here (in the textbox)
summation output should be in TXT file
Source Code :
INPUT
topup = tkinter.StringVar()
TextBox_1 = ttk.Entry(jendela, width=20, textvariable=topup)
TextBox_1.grid(column = 1, row = 3)
BUTTON
def clickhere():
f = open("TOPUP", "r")
w = f.readline()
f.close()
f = open("TOPUP", 'r+')
t=int(w)+ (topup.get())
f.write(str(t))
f.close()
button_ = ttk.Button(jendela, text='Top up!', command=lambda : clickhere, width=17)
button_.grid(column=2, row=3)

try this code:
from tkinter import *
root= Tk()
topup = StringVar()
TextBox_1 = Entry(root, width=20, textvariable=topup)
TextBox_1.grid(column = 1, row = 3)
def clickhere():
f = open("TOPUP.txt", "r+")
w = f.readline()
t=int(w)+ int(topup.get())
f.seek(0)
f.truncate()
f.write(str(t))
f.close()
button_ = Button(root, text='Top up!', command=clickhere, width=17)
button_.grid(column=2, row=3)

Related

Restore inputs previous session attributes in tkinter

Is there a way to restore the same previous session attributes in tkinter ? for example: having one button to restore the previous session attributes
Is there a way to set inputtxt to the value?
def restore():
file1 = open('user.txt', 'r')
Lines = file1.readlines()
unverified_file = Lines[0]
**inputtxt1.set(unverified_file)**
AttributeError: 'Text' object has no attribute 'set'
Looking at your updated code, you need insert not set. But first delete the entry -
def restore():
file1 = open('user.txt', 'r')
Lines = file1.readlines()
unverified_file = Lines[0]
inputtxt1.delete(0,'end')
inputtxt1.insert('end',unverified_file)
Also, take a look at this example -
import tkinter as tk
root = tk.Tk()
def save():
a = entry1.get()
b = entry2.get()
with open('1.txt','w') as f:
f.write(a)
f.write('\n')
f.write(b)
def restore():
with open('1.txt','r') as f:
text = f.read().split('\n')
entry1.insert('end',text[0])
entry2.insert('end',text[1])
entry1 = tk.Entry(root)
entry1.pack()
entry2 = tk.Entry(root)
entry2.pack()
button1 = tk.Button(root,text='Save Results',command=save)
button1.pack()
button2 = tk.Button(root,text='Restore Previous Results',command=restore)
button2.pack()
root.mainloop()

Tkinter entry.get() only works every 2 button clicks

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)

string formatting is not working in tkinter

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.

python tkinter interface how to create a new to show txt file

I buid a code which takes python user input and insert it into a text file when pressing apply as shown in the picture bellow
and the text file will always be updated when the user inserts a new text, how to create an new button next to apply to show up to date text file to the user
and want prevent to enter the same text
example if the text file has a (go) the program do not enter (go) again
this is my code
root = Tk()
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()
To prevent a user from inserting the same text just empty the two entries, and you can check if entries are not empty before saving to a file.
You can use a top-level window to show the file content.
Check the following example:
from tkinter import Tk, Toplevel, Button, Entry, StringVar, Text, DISABLED, END, W, E
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
ivn2 = StringVar()
inputVarName2 = Entry(root, textvariable=str(ivn2))
ivn2.set(str("text2"))
inputVarName2.grid(row=1, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get(), ivn2.get()]
if any(content_list):
print("\n".join(content_list))
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
ivn2.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
root.mainloop()
Edited to answer #IbrahimOzaeri question in comments.
You can use tkFileDialog.askopenfilename to ask user to select a file:
from Tkinter import Tk
import Tkinter, Tkconstants, tkFileDialog
root = Tk()
root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
print (root.filename)
I was trying something same but with one output
import tkinter.ttk as ttk
import tkMessageBox
root = Tk()
root.geometry("500x300")
root.title("The Gatway company")
ivn = StringVar()
inputVarName = Entry(root, textvariable=str(ivn))
ivn.set(str("text1"))
inputVarName.grid(row=0, column=0,columnspan=2)
def writetofile():
content_list = [ivn.get()]
if any(content_list):
with open("help.txt", 'r+') as inFile:
for item in content_list:
if ("%s\n" % item).encode('UTF-8') in inFile:
tkMessageBox.showwarning("Warning", "'%s': Already exists!" % item)
return
with open("help.txt", "a") as f:
for item in content_list:
f.write( ("%s\n" % item).encode('UTF-8'))
ivn.set('')
def showfile():
top = Toplevel()
top.title("help.txt")
textArea = Text(top)
scrollbar = ttk.Scrollbar(top, command=textArea.yview)
scrollbar.grid(row=0, column=1, sticky='nsew')
textArea['yscrollcommand'] = scrollbar.set
with open("help.txt", "r") as infile:
textArea.insert(END, infile.read())
textArea.grid(row=0, column=0)
textArea.config(state=DISABLED)
applyButton = Button(root, text="Apply", command=writetofile)
applyButton.grid(row=2, column=0, sticky=W+E)
applyButton.config( height = 5, width = 10 )
showButton = Button(root, text="Show", command=showfile)
showButton.grid(row=2, column=1, sticky=W+E)
showButton.config( height = 5, width = 10 )
root.mainloop()
it's same as your code but for one entry, I'm thinking to edit it in a such way that the user chooses the help.txt file like a file requester.

not getting the float answer

from tkinter import *
from datetime import datetime
import pickle
import os
##database will be with these mulas = dict{"name":["value","rate","left"]}
def _price_inputs():
filename = "datas.pk"
rupen = Tk()
rupen.title("Montessori Management System")
rupen.geometry("1600x800")
rupen.configure(bg="black")
framex = Frame(rupen, width=1600, bg="RoyalBlue4", height=100, relief=GROOVE).pack(side=TOP)
# ==++++===========================title=============================
#this is the variable for incoming
names = StringVar()
rates = IntVar()
totals = IntVar()
llb1 = Label(framex, font=("arial", 20, "italic"), bg="black", fg="green", text="STOCK MANAGEMENT",
relief=GROOVE).pack(side=TOP)
now = datetime.now()
hour = str(now.hour)
d = str("\\")
minute = str(now.minute)
second = str(now.second)
year = str(now.year)
month = str(now.month)
day = str(now.day)
time = "\t\t"+year + d + month + d + day + "\n\t\t" + hour + ":" + minute + ":"+second+"\n\n"
showing = str("#") * 100 + "\n"
def add_on():
name = names.get()
rate = float(rates.get())
total = float(totals.get())
with open(filename, "rb") as f:
dic = pickle.load(f)
dic[name] = [rate,total]
with open(filename, "wb") as f:
pickle.dump(dic, f)
names.set("")
rates.set("")
totals.set("")
"""with open(filename, "rb") as f:
dic = pickle.load(f)
lbl.insert(END, "\n")
lbl.insert(END, dic)
print(dic)"""
#_price_inputs()
#add_fun()
rupen.destroy()
_price_inputs()
def _sold():
nam = names.get()
rat = rates.get()
total = totals.get()
total = float(total)
with open(filename, "rb") as f:
dic = pickle.load(f)
sold = dic[nam][1]
dic[nam][1] = sold - rat
with open(filename, "wb") as f:
pickle.dump(dic, f)
names.set("")
rates.set("")
totals.set("")
rupen.destroy()
_price_inputs()
def quit():
# show = "asjdfaskldjflsajdlfj"
lbl.delete(0.0, END)
rupen.destroy()
# lbl.insert(END,"asjdfaskldjflsajdlfj")
'''
rate = str(rate)
total = str(total)
with open(filename, "rb") as f:
dic = pickle.load(f)
if os.path.getsize(filename) >= 1:
dic[name] = [rate,total]
lbl.insert(END, dic)'''
lbl = Text(rupen, wrap=WORD, font=("arial", 16, "bold"), height=100, fg="red", width=100)
lbl.pack(side=RIGHT)
# show = "asjdfaskldjflsajdlfj"
with open(filename, "rb") as f:
ano = pickle.load(f)
lbl.insert(END, time)
for k, v in ano.items():
lbl.insert(END, "\n")
lbl.insert(END, k)
lbl.insert(END, "--> ")
lbl.insert(END, "\t")
lbl.insert(END, v[0])
lbl.insert(END, "\t")
lbl.insert(END, v[1])
lbl.insert(END, "\n")
'''for k, v in dic.items():
show = """{} --> rate:- {} Total:- {}
""".format(k,v[0],v[1])
lbl.insert(END, show)
'''
####################ENTRY############################
ent1 = Entry(rupen,font=("arial",16,"bold"),textvariable=names,bd=5,bg="black",fg="white")
ent1.pack(side=BOTTOM)
ent2 = Entry(rupen,font=("airal",16,"bold"),bd=5,bg="black",textvariable=rates,fg="white")
ent2.pack(side=BOTTOM)
ent3 = Entry(rupen,font=("arial",16,"bold"),bd=5,bg="black",textvariable=totals,fg="white")
ent3.pack(side=BOTTOM)
####################BUTTONS#########################
btn0 = Button(rupen,font=("arial",16,"bold"),bd=5,bg="black",text="sold",fg="white",command=_sold)
btn0.pack(side=BOTTOM)
btn = Button(rupen, font=("arial", 16, "bold"), bd=5, bg="black", fg="white", text="quit", command=quit,
relief=RAISED)
btn.pack(side=BOTTOM)
btn2 = Button(rupen, font=("arial", 16, "bold"), bd=5, bg="black", fg="white", text="Add", relief=RAISED,
command=add_on)
btn2.pack(side=BOTTOM)
def rupen_():
rupen.destroy()
#with open("filename.pk", "wb") as f:
#pickle.dump(f, data)
# pass
rupen.mainloop()
if __name__ == "__main__":
_price_inputs()
I have this tkinter code where i can add the items with the item name rate and Total. I am not getting the float answer while clicking add or sold button.
Suppose i want to add the item1 with 12.3 rate and Total 10.5 and after i click the add button it only adds 12.0 and 10.0 the value after the . is lost.
You can't upcast an integer to a float and not expect to lose data.
rate = float(rates.get())
total = float(totals.get())
The code piece above doesn't get the float values entered back. Because you downcast float values to integers first, losing the data after .. Instead, use DoubleVar as opposed to IntVar from the very beginning:
rates = DoubleVar()
totals = DoubleVar()
You can get that by using string formatting. This "%.2f" means two decimal places after the value.
Replace this
dic[name] = [rate, total]
with this
dic[name] = ["%.2f"%rate, "%.2f"%total]
all you can add all variable for the float with the string formatting
"%.2f"
This small example to demonstrate to you how to use string formatting when use convert an Integer to float want to get two decimal places
from tkinter import *
def sum():
two_decimal = float(e1.get())- float(e2.get())
print(two_decimal) # this will print with only one decimal place
print("%.2f"%two_decimal) # this will print with only two decimal places
root = Tk()
e1 = Entry(root)
e1.insert(0, 400)
e1.pack()
e2 = Entry(root)
e2.insert(0, 200)
e2.pack()
b = Button(root, text="Want to get float value", command=sum)
b.pack()
root.mainloop()

Categories

Resources