通过另一个函数或从第一个函数外部更新函数中的值?

Updating a value in a function through another function or from outside of the first function?

我写了一个非常简单的代码来绘制散点图。我想知道如何通过 second function 引入新的 y-axis 并更新图形来替换图形。在此示例中,我可以根据 x, y1 的值进行绘图。我想知道如果我通过另一个函数得到新的值如y2,如何更新数字?

from tkinter import *
import matplotlib.pyplot as plt

root = Tk()

def plot():
    x = [1,2,3,4,5,6,7,8,9]
    y1 = [1,2,3,4,5,6,7,8,1]
    plt.scatter(x, y1)

    plt.title('Test')
    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()

def update():
    y2 = [1, 2, 3, 4, 5, 4, 3, 2, 1]

my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()

my_button2 = Button(root, text="update", command=update)
my_button2.pack()

root.mainloop()

将 Y 值设置为全局变量。你也可以让 x 自动适应这个的长度,而不是 hard-coding 9 个元素。

from tkinter import *
import matplotlib.pyplot as plt

root = Tk()

y_values = [1,2,3,4,5,6,7,8,1]

def plot():
    x = list(range(1, len(y_values)+1))
    plt.scatter(x, y_values)

    plt.title('Test')
    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()

def update():
    global y_values
    y_values = [1, 2, 3, 4, 5, 4, 3, 2, 1]

my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()

my_button2 = Button(root, text="update", command=update)
my_button2.pack()

root.mainloop()

如果将数据移动到参数中,您可以调用该函数两次,这将在第一个 window 被关闭后绘制新图形:

x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,1]

def plot(x, y):
    plt.scatter(x, y)
    plt.title('Nuage de points avec Matplotlib')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.savefig('ScatterPlot_01.png')
    plt.show()

plot(x, y)

y2 = [1,2,3,4,5,4,3,2,1]
plot(x, y2)

如果你想有不同的标题或保存到不同的.png,你可以进一步添加参数到plot():

title = 'Nuage de points avec Matplotlib part2'
filename = 'ScatterPlot_02.png'

def plot(x, y, title, filename):
    plt.scatter(x, y)
    plt.title(title)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.savefig(filename )
    plt.show()

plot(x, y2, title, filename)

您需要使用全局 y 列表。 plot()函数读取那个全局变量,update()函数更新那个全局变量(然后用plt.clf()清除数字后调用plot()):

from tkinter import *
import matplotlib.pyplot as plt

root = Tk()

x = [1,2,3,4,5,6,7,8,9]
y = [1,2,3,4,5,6,7,8,1]

def plot():
    # if you want it to be reversible, add :
    # global y
    # y = [1,2,3,4,5,6,7,8,1]
    # plt.clf()

    plt.scatter(x, y)

    plt.title('Test')
    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()

def update():
    global y
    y = [1, 2, 3, 4, 5, 4, 3, 2, 1]
    plt.clf()
    plot()

my_button1 = Button(root, text="plot", command=plot)
my_button1.pack()

my_button2 = Button(root, text="update", command=update)
my_button2.pack()

root.mainloop()