Python Forum
How to define a method in a class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to define a method in a class
I copied this code from
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:
Traceback (most recent call last):
File "", line 33, in <module>
File "", line 28, in main
ex = GraphWin()
File "", line 7, in __init__
File "", 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!

from tkinter import Tk, Canvas, Frame, BOTH

class GraphWin(Frame):
	def __init__(self):
	def dec3hex2(self,d):
			#code to convert dec to hex
			self.d = d
			hexs = str(self.d)
			return hexs 
	def initUI(self): 
		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()

if __name__ == '__main__':
I think it needs to be called like this: self.dec3hex2(10)
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):
    def method_2(self, number):
        doubled = number * 2
        print('Doubled:' , doubled)
        return doubled

cl = MyClass()
doubled = cl.method_2(10)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."

Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyQt] I get a name Name Error: when calling a method inside a class radoo 2 725 Jun-11-2020, 05:02 PM
Last Post: radoo
  [Tkinter] Issue with calling a Class/Method in GUI File Fre3k 3 983 Mar-08-2020, 12:35 PM
Last Post: Fre3k
  [Kivy] How do I reference a method in another class? Exsul1 3 1,500 Mar-02-2020, 07:32 PM
Last Post: Exsul1
  [Tkinter] Call a class method from another (Tk GUI) class? Marbelous 3 2,445 Jan-15-2020, 06:55 PM
Last Post: Marbelous
  [Tkinter] Class with text widget method AeranicusCascadia 3 5,503 Nov-14-2017, 11:33 PM
Last Post: AeranicusCascadia
  [PyQt] How to put class method into new module? California 0 1,761 Jan-18-2017, 04:05 PM
Last Post: California

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020