Home > Software design >  Plotting points from a TKinter form
Plotting points from a TKinter form

Time:11-24

I'm trying to learn GUIs in Python and trying to populate a plot as a test; I could get the random input to behave (see Add Red) but despite the x and y being fed in correctly (verified as print statements in debugging) the blue points snap to the origin and reset it to those values.

What am I missing here? Thanks.

import tkinter as tk
import numpy as np
import matplotlib as plt

plt.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

root = tk.Tk()
root.title("Main Window")

figure = Figure()
plot = figure.add_subplot(111)
plot.set_xlim(0, 100)
plot.set_ylim(0, 100)
plot.grid(which='both', visible=True)
canvas = FigureCanvasTkAgg(figure, root)

def openBlueWindow():
    newWindow = tk.Toplevel(root)
    newWindow.title("New Blue Platform")
    a = tk.Label(newWindow ,text = "X Coordinate (0-100").grid(row = 0,column = 0)
    b = tk.Label(newWindow ,text = "Y Coordinate (0-100)").grid(row = 1,column = 0)
    a1 = tk.Entry(newWindow)
    a1.grid(row = 0,column = 1)
    b1 = tk.Entry(newWindow)
    b1.grid(row = 1,column = 1)
    btn = tk.Button(newWindow, text="Add", command = lambda: add_blue(x = a1.get(), y = b1.get())).grid(row=2, column=0)
def add_blue(x,y):
    plot.scatter(x, y, marker = (3,0), color="Blue")
    canvas.draw()

def add_red():
    x = np.random.randint(0, 101)
    y = np.random.randint(0, 101)
    plot.scatter(x, y, marker=(3, 0), color="Red")
    canvas.draw()

blueButton = tk.Button(root, text="Add Blue", command=openBlueWindow)
redButton = tk.Button(root, text="Add Red", command=add_red)

canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
blueButton.pack()
redButton.pack()
root.mainloop()

CodePudding user response:

The issue is you are passing strings to the scatter function.

You can change the scatter plot line to ...

plot.scatter(float(x), (y), marker = (3,0), color="Blue")

Alternatively, you can define the variable for the entries to be doubles.

The end of your openBlueWindow function would then look like this.

    ad = tk.DoubleVar(value=0)
    bd = tk.DoubleVar(value=0)
    a1 = tk.Entry(newWindow,textvariable=ad)
    a1.grid(row = 0,column = 1)
    b1 = tk.Entry(newWindow,textvariable=bd)
    b1.grid(row = 1,column = 1)
    tk.Button(newWindow, text="Add", command = lambda: add_blue(x = ad.get(), y = bd.get())).grid(row=2, column=0)

and you would not need to specify float in the scatter function.

  • Related