matplotlib/tkinter如何在tkinter条目中显示图形

2024-09-30 20:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我把这段代码放在一起,要求在一个Tkinter条目中输入。我希望第三个条目是图形,但我似乎无法将图形放入窗口,而不是它自己的

忽略进入Tkinter网格的前两行的内容,我不知道从这里到哪里去。我假设我需要使用一些画布,这就是它被导入的原因,但我不知道我是否可以用那种方式复制这个图形

#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

Tags: fromimportfalseinputmatplotlibcolumnpltwindow
1条回答
网友
1楼 · 发布于 2024-09-30 20:23:26

您需要使用FigureCanvasTkAgg嵌入图形。它是一个canvas图,可以在上面绘制matplotlib

您已导入它,但尚未使用它。要显示它,请执行以下操作:

graph_1 = FigureCanvasTkAgg(fig, master=window)
graph_1.get_tk_widget().grid(row = 3, column = 0)
graph_1.draw()

相关问题 更多 >