Python customtkinter and Matplotlib

41 views Asked by At

I'm new to Python, and trying to learn how to combine tkinter and matplotlib. I have a code that plots triangle function when button is pressed and plots trapz function when second button is pressed. How can I make that when both buttons are pressed, both functions are shown in the same plot? Does anyone have any experience with this topic?

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

There are 1 answers

0
user18 On

Both Triangle_function() and Trapz() call plot(). However, plot() creates a new figure and new subplot each time it is called:

def plot(MF):
    fig = Figure()

    plot1= fig.add_subplot(111)

Therefore, both functions cannot draw to the same figure. This should be refactored to get the behaviour you are looking for