Python Forum

Full Version: How do I open a file and the plot it?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to create a GUI that allows me to read a text file into a variable by pressing a button. Then, I want to plot a histogram out of the data from the text file. The text file is just a 1D array of many values. Here is what I have so far:
    from tkinter import *
    from tkinter import ttk
    from tkinter import filedialog
    import matplotlib.pyplot as plt
    
    root = Tk()
    root.geometry('800x800')
    
    def openfile():
        global peaks
        filename = filedialog.askopenfilename()
        peaks = open(filename).read()
    
    def plot():
        fig2,ax2 = plt.subplots()
        ax2.hist(peaks,1000)
    
    button = ttk.Button(root, text="Open", command=openfile)
    button.grid(column=1, row=1)
    
    plot = ttk.Button(root,text='Plot',command = plot)
    plot.grid(column=2,row=1)
    
    root.mainloop()
From what I have at the moment, it seems like I can open a file, but I am not sure if it is being read into the global variable peaks. Then, when I press the Plot button, the code just stalls and then crashes. I need help with figuring out what I am doing wrong. Thank you.

Note: this is my first time dealing with Tkinter, so if there are better way to do this, I am open to suggestions.
Try importing 'loadtext' from numpy so you can input your text as data (float) into the histogram function. You won't need to define 'peaks' anymore.

Hopefully that will do it for you