1

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'
3
  • 1
    the way to define the class is strange. how did you call it? Commented Jul 30, 2021 at 8:05
  • 1
    You need to include your full code, inc. where the line that generated the error message come from? Commented Jul 30, 2021 at 8:07
  • root = window('640x640', 'Root Window') root.button(root, 'test', "0", "0") Commented Jul 30, 2021 at 8:07

2 Answers 2

1

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

window = tkinter.Tk()
Sign up to request clarification or add additional context in comments.

2 Comments

He need to import also Button, the better way is to import tkinter like this: import tkinter as tk and then change the code.
yes that changes code to window = tk.Tk() he still needs to give the file name. even for the button
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.