Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python 3.x - Use tkinter button to populate a coordinate in a scatterplot

I am new to tkinter and I am trying to build a simple code to plot some coordinates in a scatter plot. I managed well to plot one single entry but I do not find how to proceed to add some more directly in the graph when clicking the "Add in chart" button that I have created. In addition, it would be great to add the name of the item close to the point and the color that it is also indicated manually. Can someone guide me on how to proceed?

Thanks in advance for your help,

Below my code so far that should work correctly:

CODE

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
import matplotlib.pyplot as plt

root= tk.Tk()
  
canvas1 = tk.Canvas(root, width = 800, height = 500)
canvas1.pack()

label0 = tk.Label(root, text='Graphical interface',font='bold')
label0.config(font=('Arial', 12))
canvas1.create_window(400, 25, window=label0)

# Give name of activity - text label  
label_item = tk.Label(root,text = "item")  
label_item.pack()
canvas1.create_window(400, 80, window=label_item) 
# Give entry 1
item_name = tk.Entry (root,bd = 2)
item_name.pack()
canvas1.create_window(400, 110, window=item_name) 

# Give name component 1
label_x = tk.Label(root,text = "Indicate the x")
label_x.pack()
canvas1.create_window(400, 150, window=label_x) 
# Insert slider 1
myslider_x = Scale(root, from_=0, to=100, orient=HORIZONTAL, tickinterval=50)
canvas1.create_window(400, 190, window=myslider_x) 

# Give name component 2
label_y = tk.Label(root,text = "Indicate the y")
label_y.pack()
canvas1.create_window(400, 210, window=label_y) 
# Insert slider 2
myslider_y = Scale(root, from_=0, to=100, orient=HORIZONTAL, tickinterval=50)
canvas1.create_window(400, 250, window=myslider_y) 

# Give name component 3
label_color = tk.Label(root,text = "Select the color of the item")
label_color.pack(pady=30)
canvas1.create_window(400, 290, window=label_color) 
# Insert dropmenu 
clicked= StringVar() #Access the Menu Widget using StringVar function
color_menu = OptionMenu(root, clicked, "red","blue","green")
color_menu.pack()
canvas1.create_window(400, 320, window=color_menu) 

def add_to_chart():
    global x1
    global x2
    global item_name
    
    item = item_name.get()
    x1 = float(myslider_x.get())
    x2 = float(myslider_y.get())
       
    # data = {'Synergy_rate': [x1],'Innovation_rate': [x2]}  
    # df = pd.DataFrame(data,columns=['Synergy_rate','Innovation_rate'])
    
    figure1 = plt.Figure(figsize=(5,4), dpi=100)
    ax1 = figure1.add_subplot(111)
    ax1.scatter(x1,x2, color = 'r',zorder=3)
    scatter1 = FigureCanvasTkAgg(figure1, root) 
    scatter1.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH)
    ax1.legend([item]) 
    ax1.set_xlabel('x')
    ax1.set_ylabel('y')
    ax1.set_title('x vs. y')
    # Set the limit for each axis
    ax1.set_xlim([0, 100])
    ax1.set_ylim([0, 100])
    ax1.grid()
    ax1.axvspan(0, 33, 0, 0.33, color = "powderblue", alpha=1,zorder=1)
    ax1.axvspan(33, 66, 0, 0.33, color = "palegreen", alpha=1,zorder=1)
    ax1.axvspan(0, 66, 0.33, 0.66, color = "palegreen", alpha=1,zorder=1)
    ax1.axvspan(66, 100, 0, 0.66, color = "darkgreen", alpha=1,zorder=1)
    ax1.axvspan(0, 100, 0.66, 1, color = "darkgreen", alpha=1,zorder=1)
    
# Insert action buttons
        
button1 = tk.Button (root, text='Add in Chart',command=add_to_chart, bg='darkgreen',fg = 'white', font=('Arial', 10, 'bold')) 
canvas1.create_window(400, 430, window=button1)

button2 = tk.Button (root, text='Exit Application', command=root.destroy, bg='lightsteelblue2', font=('Arial', 10, 'bold'))
canvas1.create_window(400, 460, window=button2)

root.mainloop()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have finally managed to find the specific code to deal with my request. I add it below in case someone else finds it also usefull.

get_ipython().magic('reset -sf')


import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from tkinter import *
import pandas as pd



root= tk.Tk()

main_fig = Figure(figsize=(5,4), dpi=100)

axis = main_fig.add_subplot(111)
axis.plot(-10,'o-', label='class1',color='w')
axis.plot(-10,'o-', label='class2',color='b')
axis.plot(-10,'o-', label='class3',color='r')
axis.legend(loc='best', fancybox=True, framealpha=0.5)


axis.set_xlabel('x')
axis.set_ylabel('y')
axis.set_title('title') 

# Set the limit for each axis
axis.set_xlim([0, 100])
axis.set_ylim([0, 100])
axis.grid()
axis.axvspan(0, 33, 0, 0.33, color = "powderblue", alpha=1,zorder=1)
axis.axvspan(33, 66, 0, 0.33, color = "palegreen", alpha=1,zorder=1)
axis.axvspan(0, 66, 0.33, 0.66, color = "palegreen", alpha=1,zorder=1)
axis.axvspan(66, 100, 0, 0.66, color = "darkgreen", alpha=1,zorder=1)
axis.axvspan(0, 100, 0.66, 1, color = "darkgreen", alpha=1,zorder=1)

# Create figure in the canvas
scatter = FigureCanvasTkAgg(main_fig, master = root) 
toolbar = NavigationToolbar2Tk(scatter, root)
toolbar.update()
    
# Create main canvas    
canvas1 = tk.Canvas(root, width = 800, height = 500)
canvas1.pack()

label0 = tk.Label(root, text='Graphical interface',font='bold')
label0.config(font=('Arial', 12))
canvas1.create_window(400, 25, window=label0)



# Give name of activity - text label  
label_activity = tk.Label(root,text = "item")  
label_activity.pack()
canvas1.create_window(400, 80, window=label_activity) 
# Give entry 1
activity_name = tk.Entry (root,bd = 2)
activity_name.pack()
canvas1.create_window(400, 110, window=activity_name) 

# Give name component 1
label_Innovation_tech = tk.Label(root,text = "class1")
label_Innovation_tech.pack()
canvas1.create_window(400, 150, window=label_Innovation_tech) 
# Insert slider 1
myslider_Innovation_tech = Scale(root, from_=0, to=100, orient=HORIZONTAL, tickinterval=50)
canvas1.create_window(400, 190, window=myslider_Innovation_tech) 

# Give name component 2
label_Innovation_market = tk.Label(root,text = "class2")
label_Innovation_market.pack()
canvas1.create_window(400, 210, window=label_Innovation_market) 
# Insert slider 2
myslider_Innovation_market = Scale(root, from_=0, to=100, orient=HORIZONTAL, tickinterval=50)
canvas1.create_window(400, 250, window=myslider_Innovation_market) 

# Give name component 3
label_maturity_level = tk.Label(root,text = "class3")
label_maturity_level.pack(pady=30)
canvas1.create_window(400, 290, window=label_maturity_level) 

# Insert dropmenu 
clicked= tk.StringVar(root) #Access the Menu Widget using StringVar function
clicked.set('Click to see dropmenu')
maturity_menu = OptionMenu(root, clicked, "type1","type2","type3")
maturity_menu.pack()
canvas1.create_window(400, 320, window=maturity_menu) 


     
def add_to_chart():
 
    activity_name_text = activity_name.get()

    x1 = float(myslider_Innovation_tech.get())
    x2 = float(myslider_Innovation_market.get())
    maturity_lvl = clicked.get()

    # Set legend color
    color = 'r'

    if maturity_lvl == "class1":
        color = 'w'
    elif maturity_lvl == "class2":
        color = 'b'
    elif maturity_lvl == "class3":
        color = 'r'
          
    axis.scatter(x1,x2, color = color,zorder=3)
    axis.annotate('%s' % (activity_name_text), xy=(x1, x2), xytext=(0, -10),textcoords='offset points', ha='center', va='top')
    
    scatter.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH) # start plotting window only after first Add_to_chart click
    scatter.draw()  
    

  
button1 = tk.Button (root, text='Add in Chart',command=add_to_chart, bg='darkgreen',fg = 'white', font=('Arial', 10, 'bold')) 
canvas1.create_window(400, 430, window=button1)

button2 = tk.Button (root, text='Exit Application', command=root.destroy, bg='lightsteelblue2', font=('Arial', 10, 'bold'))
canvas1.create_window(400, 460, window=button2)

root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...