Python Forum
self def - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: self def (/thread-26535.html)



self def - Agusben - May-05-2020

I have a problem with a function and the "self" statement.

from tkinter import *
import turtle
from math import cos,sin,pi

root = Tk()
root.title("Mi app")
canvas=turtle.Canvas(master=root, width=650, height=650)
canvas.grid(row=0, column=0,columnspan=1, rowspan=20,padx=5,pady=5)
pen=turtle.RawTurtle(canvas)
pen.width(3)
  
class graph:

  def __init__(self, a, b):
    self.a = a_entry.get()
    self.b = b_entry.get()

  def graph (self):
    pen.penup()
    angle = 0
    theta = 0.01
    steps = int ((100*pi/theta))
    for t in range(0,steps):
        angle+=theta
        x=(cos(self.a*angle))*(200)
        y=(sin(self.b*angle))*(200)
        pen.goto(x,y)
        pen.pendown()

a_label = Label(root, text="A:")
a_label.grid(row=0, column=1)
a_entry = Entry(root)
a_entry.grid(row=0, column=2)

b_label = Label(root, text="B:")
b_label.grid(row=1, column=1)
b_entry = Entry(root)
b_entry.grid(row=1, column=2)

graph(a_entry.get(), b_entry.get())

graph_button = Button(root, text="Graph", command=graph)
graph_button.grid(row=2, column=2)

root.mainloop()
How can I make the graph function be activated from outside the Graph class?


RE: self def - Larz60+ - May-05-2020

first create an instance of the graph class:

mygraph = graph()

then run the graph method:
mygraph.graph()


RE: self def - bowlofred - May-05-2020

You have a few things happening.

One is that on line42 you've passed in the command as graph. But the graph name is for your class. If you want to call the method, that would begraph.graph. But the method expects an instance passed in as self, so you can't call the method directly.

You could create an instance and then pass the method of that instance as your command:
g_obj = graph(a_entry.get(), b_entry.get())
 
graph_button = Button(root, text="Graph", command=g_obj.graph)
The call would work, but the problem now is that the values are read only at object initialization time, before the values in the label widgets are populated. So you'd need to get the object to read the values at a later point. Perhaps instead of passing in the current value of the widgets, pass in the widgets themselves. Then at graph time, you can read the current state of the label widgets.