我想将matplotlib放入主tkinter窗口,但是经过大量的教程之后,我仍然在努力将matplotlib放在主窗口中。
我之所以需要它是因为我试图为学校项目制作图形软件。
任何帮助将不胜感激,这是我的代码到目前为止..
from tkinter import * #importing all files from Tkinter so all libraries are avaiable
root = Tk() #root is a variable which equals a tkinter class - creates blank window
root.geometry('1600x900') # Size 1600, 900 for the window
#-----------------------------------------------------------------------
---------------
button1xy = Button(text="xy")
buttony = Button(text="y=")
buttonclrscrn = Button(text="clear screen")
buttonbestfit = Button(text="line of best fit")#labels for the buttons
button1xy.grid(row=0)
buttony.grid(row=0, column=1)
buttonclrscrn.grid(row=0, column=2)
buttonbestfit.grid(row=0, column=3) #displaying them on the screen,
grid method
menu = Menu(root)
root.config(menu=menu)
def dropdownmenu():
submenu = Menu(menu)
menu.add_cascade(label=">", menu=submenu)
submenu.add_command(label="Linear")
submenu.add_command(label="Polynomial")
submenu.add_command(label="Trigonometrical")
submenu.add_command(label="Percentage Error") #drop down menu
which appears in toolbar when button is clicked on
buttonmenu = Button(text=">", command=dropdownmenu) #label and
command for the drop down menu button
buttonmenu.grid(row=0, column=8) #grid method for it to display
#-------------------------------------------------------------------
root.mainloop() #continuously keeps window on the screen until closed
#generates window
答案 0 :(得分:2)
基本上,您正试图在Tkinter窗口中嵌入matplotlib图。需要注意的关键是你需要使用TkAgg后端进行matplotlib,这样才能在Tkinter中使用它。这是一个小例子,向您展示如何在Tkinter窗口中嵌入绘图并添加一个按钮:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import matplotlib
import math
def updateGraph():
"""Example function triggered by Tkinter GUI to change matplotlib graphs."""
global currentGraph
# Clear all graphs drawn in figure
plt.clf()
y = []
if currentGraph == "sin":
for i in x:
y.append(math.cos(i))
currentGraph = "cos"
else:
for i in x:
y.append(math.sin(i))
currentGraph = "sin"
plt.plot(x,y)
fig.canvas.draw()
# This defines the Python GUI backend to use for matplotlib
matplotlib.use('TkAgg')
# Initialize an instance of Tk
root = tk.Tk()
# Initialize matplotlib figure for graphing purposes
fig = plt.figure(1)
# Special type of "canvas" to allow for matplotlib graphing
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
# Example data (note: default calculations for angles are in radians)
x = []
for i in range(0, 500):
x.append(i/10)
y = []
for i in x:
y.append(math.sin(i))
plt.plot(x, y)
currentGraph = "sin"
# Add the plot to the tkinter widget
plot_widget.grid(row=0, column=0)
# Create a tkinter button at the bottom of the window and link it with the updateGraph function
tk.Button(root,text="Update",command=updateGraph).grid(row=1, column=0)
root.mainloop()
选择正弦/余弦波来显示Tkinter对象上的触发器,例如:按钮,可以操纵matplotlib图。
尝试在Tkinter中嵌入matplotlib时,这些链接非常有用:
答案 1 :(得分:0)