Python customtkinter与Matplotlib
我刚开始学习Python,想要了解如何把tkinter和matplotlib结合起来。我有一段代码,当按下一个按钮时,它会绘制三角函数;当按下第二个按钮时,它会绘制梯形函数。我想知道怎么才能在按下两个按钮时,把这两个函数都显示在同一个图上?有没有人有这方面的经验?
from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
import customtkinter as ctk
import numpy as np
def plot(MF):
fig = Figure()
plot1= fig.add_subplot(111)
fig.set_facecolor("grey")
fig.set_edgecolor("blue")
plot1.plot(MF)
canvas = FigureCanvasTkAgg(fig, win)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, win)
toolbar.update()
toolbar.place(relx=0.2, rely=0.4)
canvas.get_tk_widget().place(relx=0.05, rely=0.4)
def Triangle_function():
a = 100
b = 500
c = 700
MF = np.zeros(1000)
for x in range(1000):
if x < a:
MF[x] = 0
elif x >= a and x <= b:
MF[x] = (x-a)/(b-a)
elif x >= b and x <= c:
MF[x] = (c-x)/(c-b)
elif x > c:
MF[x] = 0
plot (MF)
def Trapz():
a = 100
b = 500
c = 700
d = 900
MF = np.zeros(1000)
for x in range(1000):
if x < a:
MF[x] = 0
elif x >= a and x < b:
MF[x] = (x-a)/(b-a)
elif x >= b and x < c:
MF[x] = 1
elif x >= c and x < d:
MF[x] = (d-x)/(d-c)
elif x >= d:
MF[x] = 0
plot(MF)
win = ctk.CTk()
win.geometry("1000x1000")
win.title("Fuzzy Logic Designer")
win.resizable(False, False)
plot_Button = ctk.CTkButton(win, text="plot", command = Triangle_function)
plot_Button.pack()
plot_Button1 = ctk.CTkButton(win, text="plot", command = Trapz)
plot_Button1.pack(pady=20)
win.mainloop()
相关问题:
1 个回答
0
这段话的意思是,Triangle_function()
和 Trapz()
这两个函数都在使用 plot()
这个功能。不过,每次调用 plot()
的时候,它都会新建一个图形和一个子图。
def plot(MF):
fig = Figure()
plot1= fig.add_subplot(111)
所以,这两个函数不能在同一个图形上画东西。为了实现你想要的效果,需要对代码进行一些调整。