Reputation: 24623
I am trying to create a GUI as shown in figure below:
Following is the code:
#! /usr/bin/python3
import tkinter as tk
# CLASS FOR OWN PANEL:
class Mypanel(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# FN FOR BUTTON:
def adder():
main_label.set((panel1.entry.get() + panel2.entry.get()))
# CREATE GUI ELEMENTS:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel() # CREATE A PANEL
panel2 = Mypanel() # CREATE ANOTHER PANEL
main_label = tk.Label(main_window, text="Press button to get values.")
main_button = tk.Button(main_window, text="Get values.", command=adder)
# PACK ALL GUI ELEMENTS IN main WINDOW
panel1.pack()
panel2.pack()
main_label.pack()
main_button.pack()
# SHOW MAIN WINDOW:
main_window.mainloop()
However, it is giving following error:
$ ./guipanels.py
Traceback (most recent call last):
File "./guipanels.py", line 29, in <module>
panel1.pack()
File "/usr/lib/python3.5/tkinter/__init__.py", line 1961, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'pack'
Where is the problem and how can it be solved? Thanks for your help.
Upvotes: 1
Views: 53
Reputation: 13347
What you need is not a Tk
class but a Frame
instead :
import tkinter as tk
# CLASS FOR OWN PANEL:
class Mypanel(tk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, kwargs)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# def on_button(self):
# print(self.entry.get())
# FN FOR BUTTON:
def adder():
main_label.set((panel1.entry.get() + panel2.entry.get()))
# CREATE GUI ELEMENTS:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel(main_window) # CREATE A PANEL
panel2 = Mypanel(main_window) # CREATE ANOTHER PANEL
main_label = tk.Label(main_window, text="Press button to get values.")
main_button = tk.Button(main_window, text="Get values.", command=adder)
# PACK ALL GUI ELEMENTS IN main WINDOW
panel1.pack()
panel2.pack()
main_label.pack()
main_button.pack()
# SHOW MAIN WINDOW:
main_window.mainloop()
You can see the class Tk
as the main application, and you put widgets inside. There should be only one Tk
in a code.
Upvotes: 2
Reputation: 5825
Did you mean to subclass tk.PanedWindow
?
Try this:
class Mypanel(tk.PanedWindow):
def __init__(self, mainwindow):
super(Mypanel, self).__init__(mainwindow)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# def on_button(self):
# print(self.entry.get())
And pass the main_window
in your code to the panels:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel(main_window) # CREATE A PANEL
panel2 = Mypanel(main_window) # CREATE ANOTHER PANEL
Upvotes: 2