Reputation:
I have put together this piece of code that asks for an input in one Tkinter entry. I want the 3rd entry to be the graph, but I can't seem to get the graph to be put into window, rather than it's own.
Ignoring what goes into the first 2 rows of the Tkinter grid, I don't know where to go from here. I'm assuming I need to use some canvas which is why it's been imported but I don't know if I can reproduce this graph in that way.
#Import matplotlib modules
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
#Put image under graph
img = plt.imread("graph.png")
fig, ax1 = plt.subplots()
ax1.imshow(img, extent=[-10,10,-10,10], aspect='equal')
#Set graph ranges
plt.ylim(-10, 10)
plt.xlim(-10, 10)
#Set axis & labels
ax1.set_xlabel('NEGATIVE')
ax1.set_ylabel('HAPPY')
ax2 = ax1.secondary_xaxis('top')
ax2.set_xlabel('POSITIVE')
ax3 = ax1.secondary_yaxis('right')
ax3.set_ylabel('SAD', rotation=270, labelpad=12.5)
#Remove ticks/values
for ax in (ax1, ax2, ax3):
ax.tick_params(left=False, labelleft=False, top=False, labeltop=False,
right=False, labelright=False, bottom=False, labelbottom=False)
#Calculate score
##TESTING##
import random
posNeg=0
hapSad=0
posNeg = random.randint(-12, 12)
hapSad = random.randint(-12, 12)
if posNeg < (-10):
posNeg = (-10)
if posNeg > 10:
posNeg = 10
if hapSad < (-10):
hapSad = (-10)
if hapSad > 10:
hapSad = 10
##TESTING##
#Plot point on graph
plt.plot([posNeg], [hapSad], marker = 'o', markersize = 15, color = 'red')
from tkinter import *
#testing input function
def print_input():
user_input = entry_1.get()
label_2["text"] = user_input
#window
window = Tk()
label_1 = Label(window, text = "What's your Twitter handle?")
entry_1 = Entry(window)
button_1 = Button(window, text = "go", command = print_input)
label_2 = Label(window)
label_1.grid(row = 0, column = 0)
entry_1.grid(row = 0, column = 1)
button_1.grid(row = 0, column = 2)
label_2.grid(row = 1, column = 0)
graph_1 = plt.show()
graph_1.grid(row = 3, column = 0)
window.mainloop()
#\window
Upvotes: 0
Views: 665
Reputation: 1105
You need to embed the graph using FigureCanvasTkAgg
. It is a canvas
on which matplotlib
graphs can be drawn.
You have imported it, but have not used it. To display it, do the following:
graph_1 = FigureCanvasTkAgg(fig, master=window)
graph_1.get_tk_widget().grid(row = 3, column = 0)
graph_1.draw()
Upvotes: 1