Hi, i'm writing a project for my A-level course in python and ive come to a problem, i know the forum rules say not to expect a quick sollution and i dont want that as i like to understand things instead of doing them blindly.
i've written a class which displays a window with various widgets on it including some buttons.
what i want to know is if it is possible to have the functions for the commands of these buttons inside a different class as later on i hope to write another class that displays a different window that shares some of the same buttons.

Bellow is a simplified attempt at what im trying to do (some parts i barely understand and have been helped with but i understand mainly what its trying to do)
it comes with this error:

"TypeError: unbound method button1() must be called with Class2 instance as first argument (got nothing instead)"

from Tkinter import *

class Class1:
    def __init__(self):
        self.root=Tk()
        self.root.title("test")
        self.root.resizable(width=False, height=False)
        self.can1=Canvas(self.root, width=500, height=500, bg="black")
        self.can1.pack(expand=False, fill=X)
        b1 = Button(self.can1,text="button 1",command=Class2.button1)
        self.can1.create_window(20,20, window=b1, anchor = NW)


class Class2:
    def __init__(self):
        pass

    def button1(self):
        self.window2=Toplevel(bg = 'black')
        self.window2.title("test window 2")
        self.window2.resizable(width=False, height=False)
        self.window2.grid()
        self.can2=Canvas(self.window2, width=500, height=500, bg="black")

gui = Class1()
gui.root.mainloop()

The method Class2.button1 needs a Class2 instance to work, so you need to create an instance and you can write

obj2 = Class2()
    b1 = Button(self.can1,text="button 1",command=obj2.button1)

hey, its quite a similar issue
in my second class i have funtion that uses 'datetime' to create a variable which is a string of the current month
how would i pass this to the text atribute of a Tkinter label the first class?

This article has been dead for over six months. Start a new discussion instead.