Vitalij Sawizki
Vitalij Sawizki

Reputation: 33

Python class with tkinter

I'm trying to learn the classes in Python.

I wrote a little code with tkinter

from tkinter import *

class window():
    def __init__(self, size, title, ):
        self.size = size
        self.title = title

        window = Tk()
        window.geometry(self.size)
        window.title(self.title)

        print('a window has been created')

        window.mainloop()


    def button(self, window, text, x, y):

        self.window = window
        self.text = text
        self.x = x
        self.y = y

        button = Button(window, text=text).place(x=str(x), y=str(y))

but I get the error message:

self.tk = master.tk
AttributeError: 'window' object has no attribute 'tk'

Upvotes: 1

Views: 137

Answers (2)

Hrithik Jain
Hrithik Jain

Reputation: 36

you have to say from which file is this function or object is from

window = tkinter.Tk()

Upvotes: 1

SAL
SAL

Reputation: 545

I can't see where you write self.tk or where you called the class. Probably, you need to add self. when you declare window.

Like this:

from tkinter import *

class window:
    def __init__(self, size, title, ):
        self.size = size
        self.title = title

        self.window = Tk()
        self.window.geometry(self.size)
        self.window.title(self.title)

        print('a window has been created')
        self.window.mainloop()


    def button(self, window, text, x, y):

        self.window = window
        self.text = text
        self.x = x
        self.y = y

        button = Button(window, text=text).place(x=str(x), y=str(y))

if __name__ == "__main__":
    worker = window("500x500", "nice title") # <-- You need to call the class.

(If you need to declare a button, you can add this line on __init__ function above self.window.mainloop(): self.button(self.window, "Title", 10, 20))

Upvotes: 0

Related Questions