Python ткинтер, матплотлиб, рама, холст для рисования, - PullRequest
0 голосов
/ 29 марта 2020

Проблема: matplotlib не обновляется, так как Пользователь делает новый выбор из списка, вместо этого он добавляет подплот под предыдущим графиком и панелью инструментов. (образец изображения внизу поста, в гиперссылке я новый участник и пока не могу встраивать изображение)

# -*- coding: utf-8 -*- 
""" Created on Sun Mar 29 15:49:33 2020
@author: DELL """

import tkinter as tk #package for gui import pandas as pd #package for excel read/write import matplotlib as plt from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
#%% root = tk.Tk() #Create instance root.title("sample") #Create instance title root.geometry('800x600') #Create instance gemeotry
#frame for listbox frame1 = tk.Frame(root, bg='papaya whip') frame1.place(relx=.01, rely=.01, relwidth=.98, relheight=.50, anchor='nw')
#frame for plot frame3 = tk.Frame(root, bg='azure') frame3.place(relx=.01, rely=.5, relwidth=.98, relheight=.489, anchor='nw')
#%% xl = pd.ExcelFile("Untitled spreadsheet.xlsx") df1 = xl.parse("Sheet1") df2 = xl.parse("Sheet2")

#%% data from excel to listbox def retrievedata(): #a function
    global list_data1 #global stores variable
    list_data1 = [] #creating a emplty variable
    try:
        for f in df1['row1']: #loop state 
            listbox1.insert(tk.END, f) #input data into listbox
            list_data1.append(f)
            listbox1.select_set(0) #initial selection
    except:
        pass

#%% def onselect(evt): #funciton
    global state1 #global stores variable
    # Note here that Tkinter passes an event object to onselect()
    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
    frmcur_text1.set(value)
    entry11.delete(0, 'end') #Deletes previous entry in entry widget
    state1 = listbox1.curselection()[0] #Gets selection from the listbox
    entry11.insert(0, df1['row2'][state1]) #insert selection reference value into entry widget
    graph()#call function (to update as new user selects new new)
#%% def graph():   
    fig = plt.pyplot.Figure(figsize=(.25,.25), dpi=100)

    fig.add_subplot(111).plot([0,1], [0,df1['row2'][state1]], 'go-', label='line 1', linewidth=2) 

    canvas = FigureCanvasTkAgg(fig, master=frame3)  # A tk.DrawingArea. 
    fig.canvas.draw()
    canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.X)

    toolbar = NavigationToolbar2Tk(canvas, frame3)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP)
#%%
# LISTBOX label1 = tk.Label(frame1, text="dataset1").grid(row=1, column=1) #Creates a Label  content = tk.StringVar() #Makes content a String Variable
#%%
#Show selected currency for from in label frmcur_text1 = tk.StringVar() frmcur1 = tk.Label(frame1, textvariable=frmcur_text1, background='lightgrey').grid(row=2,column=1)
#%% listbox1 = tk.Listbox(frame1,exportselection=0)  #Creates a list box, exportselection seperates listboxs selections listbox1.grid(row=3, column=1)
#%% listbox1.bind('<<ListboxSelect>>', onselect)     cs = listbox1.curselection() frmcur_text1.set(cs)
#%%
# Create Label label11 = tk.Label(frame1, text="sel_ref").grid(row=4, column=1) #Creates a Label
#%% entry11 = tk.Entry(frame1, width = 20)# Create entry to selection (references) entry11.grid(row=5, column=1) #place onto gui
#%% root.resizable(True, True)  retrievedata() #run "retrievedata" command root.mainloop() #open the window

gui образец изображения

1 Ответ

0 голосов
/ 30 марта 2020

решение состоит в том, чтобы уничтожить фрейм и отделить окно графика и построение графика.

    # -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 15:49:33 2020

@author: DELL
"""

import tkinter as tk #package for gui
import pandas as pd #package for excel read/write
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
#%%
root = tk.Tk() #Create instance
root.title("sample") #Create instance title
root.geometry('800x600') #Create instance gemeotry
#frame for listbox
frame1 = tk.Frame(root, bg='papaya whip')
frame1.place(relx=.01, rely=.01, relwidth=.49, relheight=.49, anchor='nw')
#frame for answer
frame2 = tk.Frame(root, bg='slategray')
frame2.place(relx=.49, rely=.01, relwidth=.49, relheight=.49, anchor='nw')
#frame for plot
frame3 = tk.Frame(root, bg='azure')
frame3.place(relx=.01, rely=.5, relwidth=.98, relheight=.49, anchor='nw')
#%%
xl = pd.ExcelFile("Untitled spreadsheet.xlsx")
df1 = xl.parse("Sheet1")
df2 = xl.parse("Sheet2")

#%% data from excel to listbox
def retrievedata(): #a function
    global list_data1 #global stores variable
    list_data1 = [] #creating a emplty variable
    try:
        for f in df1['row1']: #loop state 
            listbox1.insert(tk.END, f) #input data into listbox
            list_data1.append(f)
            listbox1.select_set(0) #initial selection
    except:
        pass

#%%
def onselect(evt): #funciton
    global state1 #global stores variable
    # Note here that Tkinter passes an event object to onselect()
    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
    frmcur_text1.set(value)
    entry11.delete(0, 'end') #Deletes previous entry in entry widget
    state1 = listbox1.curselection()[0] #Gets selection from the listbox
    entry11.insert(0, df1['row2'][state1]) #insert selection reference value into entry widget
    graphwindow() 
    graph()#call function (to update as new user selects new new)
#%%
def graphwindow():   
    #frame for plot
    frame3 = tk.Frame(root, bg='azure')
    frame3.place(relx=.01, rely=.5, relwidth=.98, relheight=.49, anchor='nw')
    global fig
    global canvas
    global toolbar
    fig = plt.Figure(figsize=(1,2), dpi=100)

    canvas = FigureCanvasTkAgg(fig, master=frame3)  # A tk.DrawingArea. 
    fig.canvas.draw()

    canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.X)

    toolbar = NavigationToolbar2Tk(canvas, frame3)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP)


 #%% a plot
def graph():    
    try: 
        frame3.destroy()
        frame3.pack_forget()
        frame3.grid_forget()
    except:
        fig.add_subplot(111).plot([0,1], [0, df1['row2'][state1]], 'go-', label='line 1', linewidth=2) 


#%%
# LISTBOX
label1 = tk.Label(frame1, text="dataset1").grid(row=1, column=1) #Creates a Label 
content = tk.StringVar() #Makes content a String Variable
#%%
#Show selected currency for from in label
frmcur_text1 = tk.StringVar()
frmcur1 = tk.Label(frame1, textvariable=frmcur_text1, background='lightgrey').grid(row=2,column=1)
#%%
listbox1 = tk.Listbox(frame1,exportselection=0)  #Creates a list box, exportselection seperates listboxs selections
listbox1.grid(row=3, column=1)
#%%
listbox1.bind('<<ListboxSelect>>', onselect)    
cs = listbox1.curselection()
frmcur_text1.set(cs)
#%%
# Create Label
label11 = tk.Label(frame1, text="sel_ref").grid(row=4, column=1) #Creates a Label
#%%
entry11 = tk.Entry(frame1, width = 20)# Create entry to selection (references)
entry11.grid(row=5, column=1) #place onto gui
#%% close application and saves data
def close():
    root.destroy() #close window and all tabs
#%% 
#buttons
bclose = tk.Button(frame2, text="Close", command=close)
bclose.grid(row=5, column=1) #place onto gui
#%%
root.resizable(True, True) 
retrievedata() #run "retrievedata" command
root.mainloop() #open the window
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...