Reputation: 33
I am looking for some guidance on where to look up some information on creating a gui in tkinter for graphs that I have already program in python. What I would like to do is to build a gui that can import csv data and then the user would click a button that would display the type of graph they would want. Right now I have 4 graphs that I have created in python and I am not sure how to bring them over to tkinter format. I am very new to python and tkinter. Any guidance would be greatly appreciated. Here is the code I have made so far for tkinter.
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import *
import pandas as pd
import subprocess
import webbrowser
import sys
def import_csv_data():
global v
csv_file_path = askopenfilename()
print(csv_file_path)
v.set(csv_file_path)
df = pd.read_csv(csv_file_path)
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)
tk.Button(root, text='Close',command=root.destroy).grid(row=1, column=1)
tk.Button(root, text='Graph 1', command=doNothing).grid(row=3, column=0)
tk.Button(root, text='Graph 2', command=doNothing).grid(row=3, column=1)
tk.Button(root, text='Graph 3', command=doNothing).grid(row=3, column=2)
tk.Button(root, text='Graph 4', command=doNothing).grid(row=3, column=3)
def doNothing():
print("nothing")
def create_window():
window = tk.Tk()
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=create_window)
subMenu.add_command(label="Open", command=doNothing)
subMenu.add_command(label="Restart", command=doNothing)
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=doNothing)
root.mainloop()
Here is the code I have written for 1 of my graphs
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('csv.data')
# Indicated your x values and y values.
x = df["X Data"]
y1 = df["Y1 Data"]
y2 = df["Y2 Data"]
z = df["Y3 Data"]
y_pos = np.arange(len(x))
lns1 = plt.bar(y_pos,z)
plt.ylabel('Bar Graph')
plt.xlabel('Date')
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('Line Data')
plt.xticks(y_pos, x)
plt.xlabel('X axis')
plt.title('Graph 1')
plt.legend([lns1, lns2[0], lns3[0]],["Bar", "Line 1", "Line 2"], loc="upper right")
plt.draw()
plt.show()
Upvotes: 0
Views: 24264
Reputation: 11
import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
button = tkinter.Button(master=root, text="Quit", command=root.quit)
# Packing order is important. Widgets are processed sequentially and if there
# is no space left, because the window is too small, they are not displayed.
# The canvas is rather flexible in its size, so we pack it last which makes
# sure the UI controls are displayed as long as possible.
button.pack(side=tkinter.BOTTOM)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
tkinter.mainloop()
#This is the basic framework type code that helped me. You can use it according to your code.
Upvotes: 1
Reputation: 983
Here is one way of doing it (You did not say you want to display the graph in the tkinter window so I assume the graph will be displayed in a separate matplotlib window):
display_graph
, which takes the csv
file as an argument. I then
saved that module as graph1.py
.Here is the graph1.py
code:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Put the code in a function so you cal call it later
def display_graph(data):
df = pd.read_csv(data)
# Indicated your x values and y values.
x = df["X Data"]
y1 = df["Y1 Data"]
y2 = df["Y2 Data"]
z = df["Y3 Data"]
y_pos = np.arange(len(x))
lns1 = plt.bar(y_pos,z)
plt.ylabel('Bar Graph')
plt.xlabel('Date')
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('Line Data')
plt.xticks(y_pos, x)
plt.xlabel('X axis')
plt.title('Graph 1')
plt.legend([lns1, lns2[0], lns3[0]],["Bar", "Line 1", "Line 2"], loc="upper right")
plt.draw()
plt.show()
#display_graph('data.csv')
graph1.py
module into the tkinter gui file using
import graph1
graph_1
and called display_graph
from graph1
module in it.graph_1
.Here is the code for the tkinter gui:
Note: I'm using python 2.7 so I changed some of the import statements, you'll have to change them back to the python 3 equivalent.
#import Tkinter as tk
#from tkFileDialog import askopenfilename
#from Tkinter import *
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import *
import pandas as pd
import subprocess
import webbrowser
import sys
import graph1 # import the graph1 module
def import_csv_data():
global v
csv_file_path = askopenfilename()
print(csv_file_path)
v.set(csv_file_path)
df = pd.read_csv(csv_file_path)
# Define the functions before calling them
def doNothing():
print("nothing")
def create_window():
window = tk.Tk()
# Define a function for 'Graph 1' button. This just calls the 'display_graph' function from
# the 'graph1' module.
## You could avoid defining this function and use lambda and graph1.display_graph(v.get())
## in the 'Graph 1' button command but I prefer it this way.
def graph_1():
graph1.display_graph(v.get())
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)
tk.Button(root, text='Close',command=root.destroy).grid(row=1, column=1)
tk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0) # Call the graph_1 function
tk.Button(root, text='Graph 2', command=doNothing).grid(row=3, column=1)
tk.Button(root, text='Graph 3', command=doNothing).grid(row=3, column=2)
tk.Button(root, text='Graph 4', command=doNothing).grid(row=3, column=3)
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=create_window)
subMenu.add_command(label="Open", command=doNothing)
subMenu.add_command(label="Restart", command=doNothing)
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=doNothing)
root.mainloop()
This is the output when I run the gui script, browse for a csv file and click on the 'Graph 1' button:
Sample csv file
X Data,Y1 Data,Y2 Data,Y3 Data
0,5,15,100
2,6,30,125
4,4,20,122
6,10,45,128
8,15,10,79
10,14,10,84
13,20,12,99
14,6,13,56
16,4,18,67
18,8,25,83
20,9,12,91
Tkinter gui
Matplotlib graph
Upvotes: 2