Home > Software engineering >  How do I save the previous input in the text document in tkinter python
How do I save the previous input in the text document in tkinter python

Time:12-08

I am new to GUI programming and I'm trying to create a graph that takes in user input simultaneously while plotting the points given. I am still at the start, I am taking double entries and turning them into a list of tuples, and saving the entries in a text document. I have worked this all out but as I keep giving new input, the text document is erasing the previous input. Can you tell me how to save the previous inputs so I can use them to plot graphs?

here is my code till now, I'm working on y=mx c graph for now:

from tkinter import *
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math 
import numpy as np
from random import randint
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

matplotlib.use('TkAgg')

x=[]
m =[]
mywidgets=[]

def get_entry():
    with open('data.txt', 'w') as out:
        for E1, E2 in mywidgets:
            out.write(E1.get() " " E2.get() '\n')

root = Tk()
root.title("Y=mX c Graph")
label1= Label(root,text="m").grid(row=0,column=0)
label2 =Label(root,text="x").grid(row=0,column=3)
e1 = Entry(root)
e2=Entry(root)
e1.grid(row=0, column=1, padx=5, pady=10)
e2.grid(row=0, column=4, padx=5, pady=10)
mywidgets.append((e1,e2))
button = Button(root, text="Plot the Graph",command=get_entry).grid(row=0,column=5)
root.mainloop()

CodePudding user response:

A better way to implement this program is to ask the user for values m and c, where x can span a range. For this example, make sure that the text file is in the same folder as the program.

Here is my adapted example:

from tkinter import *
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math 
import numpy as np
from random import randint
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure



#Change the path to that of your.txt file
f = open("p.txt", "r")

#Function that quits program when user closes window
def quit_me():
    print('Thank you for using the program')
    root.quit()
    root.destroy()

#Plots chart when button "Plot" is pressed
def plotData():
    
    #Clears previous chart
    plt.clf()
    #Size of chart
    fig = Figure(figsize = (4.5, 2.7),
                 dpi = 100)
    canvas = FigureCanvasTkAgg(fig,
                               master = root)  
    canvas.draw()
  
    #Turns user input into integers
    m = int(e1.get())
    c = int(e2.get())
   
    #Here you can set the range of your graph
    y = [m*x   c  for x in range(10)]
  
    #Adding the subplot
    plot1 = fig.add_subplot(111)
  
    #Plotting the graph
    plot1.plot(y)
    #Placing the canvas on the Tkinter window
    canvas.get_tk_widget().place(x=25, y=70)

    #Appends the user inputed m and c values delimited by a comma onto the chosen .txt file
    with open("p.txt", "a ") as file_object:
    #Move read cursor to the start of file.
        file_object.seek(0)
    #If file is not empty then append '\n'
        data = file_object.read(100)
        if len(data) > 0 :
            file_object.write("\n")
    #Appends text at the end of file on a new line. 
        file_object.write(("%s,%s") % (m,c))


root = Tk()

root.geometry("500x400")

#Empty Plot placeholder

fig = Figure(figsize = (4.5, 2.7),
                 dpi = 100)
canvas = FigureCanvasTkAgg(fig,
                               master = root)  
canvas.draw()
y = [0]
plot1 = fig.add_subplot(111)
plot1.plot(y)
canvas.get_tk_widget().place(x=25, y=70)
   

root.title("Y=mx c Graph")

#Label for M value
lbl=Label(root, text="Type in M Value:", fg='black', font=("Helvetica", 12))
#Position of M value label
lbl.place(x=0, y=0)

#Label for C value
lbl2=Label(root, text="Type in C Value:", fg='black', font=("Helvetica", 12))
#Position of C label
lbl2.place(x=200, y=0)

#M user input value
e1 = Entry(root)
e1.place(x=130,y=5,width=60)

#C user input value
e2 = Entry(root)
e2.place(x=330,y=5,width=60)


btn = Button(root, text="Plot", width=4, command=lambda:plotData())
btn.place(x=415, y=2)


root.protocol("WM_DELETE_WINDOW", quit_me)
root.mainloop()
  • Related