How to define a method in a class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: How to define a method in a class (/thread-5840.html) |
How to define a method in a class - 1885 - Oct-24-2017 I copied this code from zetcode.com What I want to do is call a method dec3hex2 that returns a string in the form of #000000 I have the dec to hex code completed but I get the following errors: python draw_tk_example.py Traceback (most recent call last): File "draw_tk_example.py", line 33, in <module> main() File "draw_tk_example.py", line 28, in main ex = GraphWin() File "draw_tk_example.py", line 7, in __init__ self.initUI() File "draw_tk_example.py", line 20, in initUI hexc = dec3hex2(self,10) NameError: name 'dec3hex2' is not defined How do I call a method from the mothod initUI(self): ? Thank You! #http://zetcode.com/gui/tkinter/drawing/ from tkinter import Tk, Canvas, Frame, BOTH class GraphWin(Frame): def __init__(self): super().__init__() self.initUI() def dec3hex2(self,d): #code to convert dec to hex self.d = d hexs = str(self.d) return hexs def initUI(self): self.master.title("Colors") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) #call to dec3hex2 hexc = dec3hex2(self,10) canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0") canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50") canvas.create_rectangle(270, 10, 370, 80, outline="#05f", fill="#05f") canvas.pack(fill=BOTH, expand=1) def main(): root = Tk() ex = GraphWin() root.geometry("400x100+300+300") root.mainloop() if __name__ == '__main__': main() RE: How to define a method in a class - Lux - Oct-29-2017 I think it needs to be called like this: self.dec3hex2(10)
RE: How to define a method in a class - wavic - Oct-29-2017 You define the method with self parameter but when you call it, you don't pass it. Only the positional/keyword arguments. class MyClass: def method_1(self): print('One') def method_2(self, number): doubled = number * 2 print('Doubled:' , doubled) return doubled cl = MyClass() cl.method_1() doubled = cl.method_2(10) |