代码之家  ›  专栏  ›  技术社区  ›  Snoozium

如何在Tkinter中刷新/重新启动画布以创建不同的绘图?

  •  0
  • Snoozium  · 技术社区  · 4 年前

    我在刷新图表方面有点困难,所以我能够运行直方图,然后运行箱线图。我想需要的是一个带有“.design”和“初始化窗口”的按钮,或者在每个绘图开始时都有一个刷新功能,这样就可以为新的绘图做好准备。

    我尝试了很多与stackoverflow不同的方法,但似乎都不起作用。我主要尝试了canvas.delete('all'),但它并没有真正起作用。所以我希望stackoverflow上的人知道如何在这种结构中正确工作。

    此外,我必须高度赞扬用户“j_4321”。j_4321真的帮助我弄清楚了如何在Tkinter中正确绘图以及如何初始化这个框架!

    import tkinter as tk
    from tkinter import ttk
    from tkinter import filedialog
    from tkinter import Toplevel
    from tkinter.filedialog import askopenfilename
    from tkinter.messagebox import showinfo, showwarning, askquestion
    from tkinter import OptionMenu
    from tkinter import StringVar
    
    import seaborn as sns
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
    from matplotlib.figure import Figure
    from matplotlib import style
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    import matplotlib.dates as mdates
    from psutil import cpu_percent
    from psutil import virtual_memory
    from datetime import datetime, timedelta
    
    from sklearn.metrics import silhouette_score
    from sklearn.cluster import KMeans
    import sklearn.cluster as cluster
    import scipy.spatial.distance as sdist
    from sklearn.ensemble import IsolationForest
    from sklearn.model_selection import train_test_split
    from sklearn.ensemble import GradientBoostingClassifier
    from sklearn.metrics import accuracy_score
    
    import pandas as pd
    import numpy as np
    import seaborn as sn
    
    from sklearn.preprocessing import MinMaxScaler
    from sklearn.preprocessing import StandardScaler
    
    RANDOM_STATE = 42 #used to help randomly select the data points
    low_memory=False
    LARGE_FONT= ("Verdana", 12)
    style.use("ggplot")
    
    f = Figure(figsize=(5,5), dpi=100)
    a = f.add_subplot(111)
    
    df = None
    df_nan = None
    df_r = None
    check_transformer = None
    df_output = None
    ContNum = None
    GB_Classifier_score = None
    
    df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
                       columns=['age', 'collection_agency', 'number'])
    
    class Analyticsapp(tk.Tk):
    
        def __init__(self, *args, **kwargs):
            tk.Tk.__init__(self, *args, **kwargs)
    
            #tk.Tk.iconbitmap(self, default="iconimage_kmeans.ico") #Icon for program
            tk.Tk.wm_title(self, "Advanched analytics")
    
            container = tk.Frame(self)
            container.pack(side="top", fill="both", expand=True)
            container.grid_rowconfigure(0, weight=1)
            container.grid_columnconfigure(0, weight=1)
            
            self.frames = {}
    
            for F in (StartPage, PlottingDFPage):
    
                frame = F(container, self)
    
                self.frames[F] = frame
    
                frame.grid(row=0, column=0, sticky="nsew")
    
            self.show_frame(StartPage)
    
        def show_frame(self, cont):
    
            frame = self.frames[cont]
            frame.tkraise()
    
    class StartPage(tk.Frame):
    
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)
            label = tk.Label(self, text="Advanched analytics", font=LARGE_FONT)
            label.pack(pady=10, padx=10)
            
            button4 = ttk.Button(self, text="Plot Example", 
                                command=lambda: controller.show_frame(PlottingDFPage))
            button4.pack(fill='x')
            
    class PlottingDFPage(tk.Frame):    
    
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)
            label = tk.Label(self, text="Plotting Dataframe", font=LARGE_FONT)
            label.pack(pady=10, padx=10)         
    
            global df, Plot_type, Plot_define
            
            def PlotMaster():
    
                Plot_define = Plot_type.get()
    
                if df is None:
                    showwarning("Warning", "Read file first")
                elif Plot_define == '-Choose an option-':
                    showwarning("Warning", "Choose a plot type")
                elif Plot_define == 'Histogram':
                    Plot_text = "Plot set to: "+Plot_define
                    showinfo(title="Results", message=Plot_text)
                    HistogramDF()
                elif Plot_define == 'Scatterplot':
                    Plot_text = "Plot set to: "+Plot_define
                    showinfo(title="Results", message=Plot_text)
                    ScatterplotDF()
                elif Plot_define == 'Boxplot':
                    Plot_text = "Plot set to: "+Plot_define
                    showinfo(title="Results", message=Plot_text)
                    BoxplotDF()
                else: None
            
            def HistogramDF():
                
                f = None
                f = plt.figure(figsize=(10, 8))
                
                # REMOVE AFTER DF X, y generation!!!
                ax = sns.distplot(df['age'])
    
                canvas = FigureCanvasTkAgg(f, self)
                canvas.draw()
                canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
    
                toolbar = NavigationToolbar2Tk(canvas, self)
                toolbar.update()
                canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
            
            def ScatterplotDF():
                
                f = None
                f = plt.figure(figsize=(10, 8))
                
                x = df['age']
                y = df['collection_agency']
                
                plt.scatter(x, y)
                plt.draw()
                
                canvas = FigureCanvasTkAgg(f, self)
                canvas.draw()
                canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
    
                toolbar = NavigationToolbar2Tk(canvas, self)
                toolbar.update()
                canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
            
            def BoxplotDF():
                
                f = None
                f = plt.figure(figsize=(10, 8))
                
                # REMOVE AFTER DF X, y generation!!!
                boxplot_df = df.filter(['age', 'collection_agency'])
                boxplot_columns = list(boxplot_df.columns)
            
                sns.set_style('whitegrid')
                ax = sns.boxplot(x='collection_agency',y='age',data=boxplot_df)
                ax = sns.stripplot(x='collection_agency', y='age',data=boxplot_df)
                
                canvas = FigureCanvasTkAgg(f, self)
                canvas.draw()
                canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
    
                toolbar = NavigationToolbar2Tk(canvas, self)
                toolbar.update()
                canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
    
            Options_plot = ['-Choose an option-', 'Histogram', 'Scatterplot', 'Boxplot']
                    
            Plot_type = StringVar(self)
            Plot_type.set(Options_plot[0]) # default value
            
            label1 = tk.Label(self, text='Plot type:')
            label1.pack()
            
            dropdown1 = tk.OptionMenu(self, Plot_type, *Options_plot)
            dropdown1.pack()
            
            button1 = ttk.Button(self, text="Run plot", command=PlotMaster)
            button1.pack(fill='x')
            
            button2 = ttk.Button(self, text="Back",
                               command=lambda: controller.show_frame(StartPage))
            
    app = Analyticsapp()
    app.geometry('500x400')
    app.mainloop()
    
    0 回复  |  直到 4 年前