我是 Python 新手,正在尝试学习如何结合 tkinter 和 matplotlib。我有一个代码,当按下按钮时绘制三角形函数,并在按下第二个按钮时绘制 trapz 函数。如何使两个按钮都按下时,两个函数都显示在同一个图中?有人对这个话题有经验吗?
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()
Triangle_function()
和Trapz()
都调用plot()
。然而,plot()
每次调用时都会创建一个新的图形和新的子图:
def plot(MF):
fig = Figure()
plot1= fig.add_subplot(111)
因此,两个函数无法绘制同一个图形。应该重构以获得您正在寻找的行为