Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用tkinter GUI可视化matplotlib预测?_Python_Python 3.x_Matplotlib_Tkinter_Tkinter Canvas - Fatal编程技术网

Python 如何使用tkinter GUI可视化matplotlib预测?

Python 如何使用tkinter GUI可视化matplotlib预测?,python,python-3.x,matplotlib,tkinter,tkinter-canvas,Python,Python 3.x,Matplotlib,Tkinter,Tkinter Canvas,我有一个场景,我对一个特定的数据集进行了预测。现在我想用Tkinter将预测的图形可视化 我的机器学习模型如下所示,由一个图组成: # Importing Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import sys # Importing the Batsmen Dataset dataset = pd.read_csv('Batsmen/Batsmen.csv') X

我有一个场景,我对一个特定的数据集进行了预测。现在我想用Tkinter将预测的图形可视化

我的机器学习模型如下所示,由一个图组成:

# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys

# Importing the Batsmen Dataset
dataset = pd.read_csv('Batsmen/Batsmen.csv')
X = dataset.iloc[:, [1, 2, 3, 4, 5, 6]].values

# Using Elbow Method to find the optimal number of Clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
    kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS')
plt.show()
我尝试如下所示:

from tkinter import *

# these four imports are important
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def plot():
    # Importing Libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import sys

    # Importing the Batsmen Dataset
    dataset = pd.read_csv('Batsmen/Batsmen.csv')
    X = dataset.iloc[:, [1, 2, 3, 4, 5, 6]].values

    # Using Elbow Method to find the optimal number of Clusters
    from sklearn.cluster import KMeans
    wcss = []
    for i in range(1, 11):
        kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
        kmeans.fit(X)
        wcss.append(kmeans.inertia_)

root = Tk()

def app():
    # initialise a window.
    root = Tk()
    root.config(background='white')
    root.geometry("1000x700")

    lab = Label(root, text="Live Plotting", bg = 'white').pack()

    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_title('The Elbow Method')
    ax.set_xlabel('Number of Clusters')
    ax.set_ylabel('WCSS')
    ax.grid()

    graph = FigureCanvasTkAgg(fig, master=root)
    graph.get_tk_widget().pack(side="top",fill='both',expand=True)

def plotter():
    ax.cla()
    ax.grid()
    dpts = plot()
    ax.plot(range(1, 11), wcss, marker='o', color='orange')
    graph.draw()
    time.sleep(1)

def gui_handler():
    threading.Thread(target=plotter).start()

b = Button(root, text="Start/Stop", command=gui_handler, bg="red", fg="white")
b.pack()

root.mainloop()

if __name__ == '__main__':
    app()
但它不起作用


我只想在Tkinter GUI上显示预测,当我按下GUI中的预测按钮时,我希望图形显示在GUI画布中。所以,有人能帮我做同样的事情吗。

如果我使用
root.after()
而不是线程,那么你的代码对我来说很有用

可能在大多数GUI框架中,线程应该(或不能)更改GUI中的元素

在我的计算机上,当我按下运行线程的按钮时,带有线程结尾的YRU代码就工作了

我运行
绘图仪
时不使用
睡眠
之后(1000,绘图仪)
在1000ms(1s)后再次运行


编辑:在新代码中不运行循环,因此不需要线程或
after()

但你还有其他基本问题:

您有错误的缩进,并且
mainloop()
app()
之外-它在
app()
之前执行

在以前的版本中,
绘图仪
位于
app()
内部-如果您在外部需要它,那么您的局部变量(如
ax
)有问题-您必须使用
global
才能在其他函数中访问这些变量。或者,您必须使用此值作为参数运行函数-例如,绘图仪(ax、wcss、graph)

这个版本使用
全局
,适合我。我没有你的CSV,也不想运行
sklearn
,所以我放了一些假数据

from tkinter import *

# these four imports are important
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def plot():
    # Importing Libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import sys

    # Importing the Batsmen Dataset
#    dataset = pd.read_csv('Batsmen/Batsmen.csv')
    dataset = pd.DataFrame({
        'a': range(10),
        'b': range(10),
        'c': range(10),
        'd': range(10),
        'e': range(10),
        'f': range(10),
        'g': range(10),
    })

    X = dataset.iloc[:, [1, 2, 3, 4, 5, 6]].values

    # Using Elbow Method to find the optimal number of Clusters
    from sklearn.cluster import KMeans

    global wcss
    wcss = range(1, 11)
    #wcss = []
#    for i in range(1, 11):
#        kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
#        kmeans.fit(X)
#        wcss.append(kmeans.inertia_)

def plotter():
    global wcss
    global ax
    global graph

    ax.cla()
    ax.grid()
    dpts = plot()
    ax.plot(range(1, 11), wcss, marker='o', color='orange')
    graph.draw()

def gui_handler():
    plotter()

def app():
    global ax
    global graph

    # initialise a window.
    root = Tk()
    root.config(background='white')
    root.geometry("1000x700")

    lab = Label(root, text="Live Plotting", bg = 'white').pack()

    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_title('The Elbow Method')
    ax.set_xlabel('Number of Clusters')
    ax.set_ylabel('WCSS')
    ax.grid()

    graph = FigureCanvasTkAgg(fig, master=root)
    graph.get_tk_widget().pack(side="top",fill='both',expand=True)

    b = Button(root, text="Start/Stop", command=gui_handler, bg="red", fg="white")
    b.pack()

    root.mainloop()

if __name__ == '__main__':
    app()

阅读并遵循@stovfl注释中的链接。我用这段代码创建了其他示例:@furas,我不清楚嵌入是如何完成的。你能帮我解决这个问题吗?你应该展示你已经尝试了什么,你能做什么,或者提出更精确的问题-Stackoverflow不是一个让别人为你完成整个任务的地方。你几乎没有错误,代码中没有一个错误-所以当你只修复一个错误时,它仍然不起作用。请参阅我的回答中的新代码我对以前的代码感到抱歉。我贴错了。我刚刚编辑并更改为正确的代码。新代码只显示一次,因此不需要线程。如果您运行它时没有线程,那么它可能会工作。是的,我已经删除了它并运行了程序。我得到的错误如下:`ax.cla()NameError:name'ax'未定义`因为您有局部变量
ax
,您需要知道在另一个函数中如何使用它。
from tkinter import *

# these four imports are important
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

def plot():
    # Importing Libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import sys

    # Importing the Batsmen Dataset
#    dataset = pd.read_csv('Batsmen/Batsmen.csv')
    dataset = pd.DataFrame({
        'a': range(10),
        'b': range(10),
        'c': range(10),
        'd': range(10),
        'e': range(10),
        'f': range(10),
        'g': range(10),
    })

    X = dataset.iloc[:, [1, 2, 3, 4, 5, 6]].values

    # Using Elbow Method to find the optimal number of Clusters
    from sklearn.cluster import KMeans

    global wcss
    wcss = range(1, 11)
    #wcss = []
#    for i in range(1, 11):
#        kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)
#        kmeans.fit(X)
#        wcss.append(kmeans.inertia_)

def plotter():
    global wcss
    global ax
    global graph

    ax.cla()
    ax.grid()
    dpts = plot()
    ax.plot(range(1, 11), wcss, marker='o', color='orange')
    graph.draw()

def gui_handler():
    plotter()

def app():
    global ax
    global graph

    # initialise a window.
    root = Tk()
    root.config(background='white')
    root.geometry("1000x700")

    lab = Label(root, text="Live Plotting", bg = 'white').pack()

    fig = Figure()

    ax = fig.add_subplot(111)
    ax.set_title('The Elbow Method')
    ax.set_xlabel('Number of Clusters')
    ax.set_ylabel('WCSS')
    ax.grid()

    graph = FigureCanvasTkAgg(fig, master=root)
    graph.get_tk_widget().pack(side="top",fill='both',expand=True)

    b = Button(root, text="Start/Stop", command=gui_handler, bg="red", fg="white")
    b.pack()

    root.mainloop()

if __name__ == '__main__':
    app()