Reputation: 5346
How can you create a window in tkinter with a class?
i know root = Tk()
is the standard way to do it, but if i want to make a class that create a "window" in python that i can add buttons to later on who is that done?
I get this error from the code down below:
Traceback (most recent call last):
File "C:/Users/euc/PycharmProjects/Skole/Shortcut/Gui2.py", line 26, in <module>
b = Create_button(a)
File "C:/Users/euc/PycharmProjects/Skole/Shortcut/Gui2.py", line 18, in __init__
self.button = Button(window, text=text)
File "C:\Python34\lib\tkinter\__init__.py", line 2161, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2084, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python34\lib\tkinter\__init__.py", line 2062, in _setup
self.tk = master.tk
AttributeError: 'Create_window' object has no attribute 'tk'
My code:
from tkinter import *
class Create_window(): #Create a window
win = Tk()
def __init__(self):
self = Tk()
self.title("This is title Name")
class Create_button: # Create a button within the window
text = "None"
button_width = 15
button_height = 10
def __init__(self, window, text="null"):
if text == "null": #Set text to none if none parameter is passed
text = self.text
self.button = Button(window, text=text)
self.button.grid(row=0, column=0)
a = Create_window() # Create window
b = Create_button(a) # Create button within Window
a.mainloop()
Upvotes: 0
Views: 10553
Reputation: 2620
You can subclass Toplevel
to do this. Check this out for more on Toplevel
.
Also I have cleaned up and restructured your code a little. Compare your code and this and note the differences and changes made for some better practices.
Pay attention to class name conventions as opposed to method name conventions. Class names usually don't start with a verb or action word, because essentially classes are objects or nouns. Functions and methods on the other hand must start with a verb or action word.
You don't need to use a class to create a button for what looks like something that can be put in a single function.
Here's the modified snippet:
from tkinter import *
class MyWindow(Toplevel): #Create a window
def __init__(self, master=None):
Toplevel.__init__(self, master)
self.title("This is title Name")
def create_button(frame, text="None"): # Create a button within the frame given
button_width = 15
button_height = 10
frame.button = Button(frame, text=text)
frame.button. configure(height=button_height, width=button_width)
frame.button.grid(row=0, column=0)
app = Tk()
a = MyWindow(master=app) # Create window
create_button(a) # Create button within Window
app.mainloop()
Also make sure to check this out for a great tutorial on using and subclassing Toplevel to create dialogs.
Hope this helps.
Upvotes: 4