Regan Kelly Regan Kelly - 6 months ago 10
Python Question

I need help alling a def statement from another class. Python

I am having trouble trying to call a def statement from another class.

This is my first class with just a GUI tkinter combobox.

class GUI():
def __init__(self,root):
self.notebook = ttk.Notebook(root)
self.notebook.pack()

self.length_frame = ttk.Frame(self.notebook)
self.weight_frame = ttk.Frame(self.notebook)
self.temperature_frame = ttk.Frame(self.notebook)

self.notebook.add(self.length_frame, text = 'Length')

#Combobox
self.measurements = StringVar()
self.Combobox_Length_Left = ttk.Combobox(self.length_frame, textvariable = self.measurements, values = ('mm', 'cm', 'inch', 'ft', 'yd', 'm', 'km', 'mi'), width = 10,state=['readonly'])
self.Combobox_Length_Left.current(5)
self.measurements.trace('w', Convertion(self.update_length))
self.Combobox_Length_Left.grid(row = 2, column = 0, padx = 5, pady = 5, sticky = E)


I am trying to call the def statement
update length
from the other class which is here:

class Convertion:
as_meter = dict(mm=0.001, cm=0.01, inch=0.0254,ft=0.3048, yd=0.9144, m=1.0,km=1000.0, mi=1609.344,)
def update_length(self, *args):
try:
v = int(self.Text_Length_Left.get())
except ValueError:
self.Text_Length_Left.set('')
self.Text_Length_Right.set('')
return
m = v * self.as_meter [self.measurements.get()]
r = m/self.as_meter[self.measurements1.get()]
self.Text_Length_Right.set("{:.5g}".format(r))


My attempt of calling was
Covertion(self.update_length)


Thanks for any help!

Answer

My attempt of calling was Covertion(self.update_length)

If update_length is a (non-static) method of a class called Convertion, then to call it you first need to instantiate an instance of that class, then call the method on it:

c = Convertion()
c.update_length() # pass any args in there too, c.update_length(p1, p2, ...)