I am trying to build a GUI with the main Frame having nested frame containing header label (created with different class).
In below snippet, I am expecting frame created by FrameHeader class to be inside MainWindow.container Frame (while initialization of MainWindow.container attribute, container attribute is passed as parent).
Still, when the below code is run, FrameHeader frame is at the bottom after container frame, instead of being inside the container frame.
I am new to tkinter, can someone help me out here, what am I missing while going between different classes?
from tkinter import *
class FrameHeader(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, bg='red',relief=RAISED, borderwidth=2)
self.pack(fill=BOTH, side=TOP)
lblTitle = Label(self, text='Welcome to the Program!')
lblTitle.pack(fill=BOTH)
class MainWindow(Tk):
def __init__(self,*args):
Tk.__init__(self,*args)
self.geometry('400x300')
# Main Container
container=Frame(self, bg='black')
container.pack(side=TOP, expand=TRUE, fill=BOTH)
frameHeader=FrameHeader(container, self)
if __name__=='__main__':
mainWindow=MainWindow()
mainWindow.mainloop()
You are neglecting to pass parent to Frame.__init, so the parent of FrameHeader defaults to the root window rather than the container.
The code needs to be this:
Frame.__init__(self, parent, bg='red',relief=RAISED, borderwidth=2)
Related
I would like to create a contractible panel in a GUI, using the Python package tkinter.
My idea is to create a decorator for the tkinter.Frameclass, adding a nested frame and a "vertical button" which toggles the nested frame.
Sketch: (Edit: The gray box should say Parent of contractible panel)
I got it to toggle just fine, using the nested frame's grid_remove to hide it and then move the button to the left column (otherwise occupied by the frame).
Now I want to be able to use it like any other tkinter.Frame, but let it target the nested frame. Almost acting like a proxy for the nested frame. For example, adding a tkinter.Label (the green Child component in the sketch) to the decorator should add the label to the nested frame component (light yellow tk.Frame in the sketch) not the decorator itself (strong yellow ContractiblePanel in the sketch).
Minimal example: (omitting the toggling stuff and any "formatting"):
(Here's a published (runnable) Repl project)
import tkinter
class ContractiblePanel(tkinter.Frame):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self._panel = tkinter.Frame(self)
self._toggle = tkinter.Button(self, text='<', command=self._toggle_panel)
self.grid(row=0, column=0, sticky='nsw')
self._panel.grid(row=0, column=0, sticky='nsw')
self._toggle.grid(row=0, column=1, sticky='nsw')
def _toggle_panel(self):
# ...
if __name__ == '__main__':
root = tkinter.Tk()
root.geometry('128x128')
contractible_panel = ContractiblePanel(root)
Forwarding configuration calls is just overriding the config method I guess?
class ContractiblePanel(tkinter.Frame):
# ...
def config(self, **kwargs):
self._panel.config(**kwargs)
# ...
contractible_panel.config(background='blue')
But I would like to be able to add a child component into the nested panel frame by
label_in_panel = tkinter.Label(contractible_panel, text='yadayada')
How do I get the ContractiblePanel object to act like a proxy to its member _panel, when adding child components?
What other methods/use cases should I consider? I am quite new to tkinter and thus expect the current implementation to break some common practices when developing tkinter GUIs.
This is an interesting question. Unfortunately, tkinter really isn't designed to support what you want. I think it would be less complicated to simply expose the inner frame and add widgets to it.
That being said, I'll present one possible solution. It's not implemented as a python decorator, but rather a custom class.
The difficulty is that you want the instance of the custom class to represent the outer frame in one context (for example, when packing it in your UI) and the inner frame in another context (when adding child widgets to it)
The following solution solves this by making the instance be the inner frame, and then overriding pack,place, and grid so that they operates on the outer frame. This works fine, with an important exception: you cannot use this class directly inside a notebook or embedded in a text widget or canvas.
I've used colors and borders so it's easy to see the individual components, but you can remove the colors in production code, obviously. Also, I used a label instead of a button since I created the screenshot on OSX where the background color of a button can't be changed.
import tkinter as tk
class ContractiblePanel(tk.Frame):
def __init__(self, parent, **kwargs):
self._frame = tk.Frame(parent, **kwargs)
super().__init__(self._frame, bd=2, relief="solid", bg="#EFE4B0")
self._button = tk.Label(
self._frame, text="<", bg="#00A2E8", bd=2,
relief="solid", font=("Helvetica", 20), width=4
)
self._frame.grid_rowconfigure(0, weight=1)
self._frame.grid_columnconfigure(0, weight=1)
self._button.grid(row=0, column=1, sticky="ns", padx=4, pady=4)
super().grid(row=0, column=0, sticky="nsew", padx=4, pady=4)
self._button.bind("<1>", lambda event: self.toggle())
def collapse(self):
super().grid_remove()
self._button.configure(text=">")
def expand(self):
super().grid()
self._button.configure(text="<")
def toggle(self):
self.collapse() if self.winfo_viewable() else self.expand()
def pack(self, **kwargs):
# override to call pack in the private frame
self._frame.pack(**kwargs)
def grid(self, **kwargs):
# override to call grid in the private frame
self._frame.grid(**kwargs)
def place(self, **kwargs):
# override to call place in the private frame
self._frame.place(**kwargs)
root = tk.Tk()
root.geometry("400x300")
cp = ContractiblePanel(root, bg="yellow", bd=2, relief="raised")
cp.pack(side="left", fill="y", padx=10, pady=10)
label = tk.Label(cp, text="Child component", background="#22B14C", height=3, bd=2, relief="solid")
label.pack(side="top", expand=True, padx=20, pady=20)
root.mainloop()
First of all it is kinda gross to use this code and it's very confusing. So I'm really not sure if you really want to take this route. However, it is possible to achieve it.
The basic idea is to have a wrapper and to pretend the wrapper is the actual object you can lie with __str__ and __repr__ about what the class really is. That is not what a proxy means.
class WrapperClass:
def __init__(self, master=None, **kwargs):
self._wrapped_frame = tk.Frame(master, **kwargs)
self._panel = tk.Frame(self._wrapped_frame)
self._toggle = tk.Button(self._wrapped_frame, text='<', command=self._toggle_panel)
self._wrapped_frame.grid(row=0, column=0, sticky='nsw')
self._panel.grid(row=0, column=0, sticky='nsw')
self._toggle.grid(row=0, column=1, sticky='nsw')
return None
def _toggle_panel(self):
print('toggle')
def __str__(self):
return self._panel._w
__repr__ = __str__
You can do even more confusing things by delegate the lookup-chain to the _wrapped_frame inside the WrapperClass this enables you to call on the instance of WrapperFrame() methods like pack or every other method. It kinda works similar for inheritance with the difference that by referring to the object, you will point to different one.
I don't recommend using this code by the way.
import tkinter as tk
NONE = object()
#use an object here that there will no mistake
class WrapperClass:
def __init__(self, master=None, **kwargs):
self._wrapped_frame = tk.Frame(master, **kwargs)
self._panel = tk.Frame(self._wrapped_frame)
self._toggle = tk.Button(self._wrapped_frame, text='<', command=self._toggle_panel)
self._wrapped_frame.grid(row=0, column=0, sticky='nsw')
self._panel.grid(row=0, column=0, sticky='nsw')
self._toggle.grid(row=0, column=1, sticky='nsw')
return None
def _toggle_panel(self):
print('toggle')
def __str__(self):
return self._panel._w
__repr__ = __str__
def __getattr__(self, name):
#when wrapper class has no attr name
#delegate the lookup chain to self.frame
inreturn = getattr(self._wrapped_frame, name, NONE)
if inreturn is NONE:
super().__getattribute__(name)
return inreturn
root = tk.Tk()
wrapped_frame = WrapperClass(root, bg='red', width=200, height=200)
root.mainloop()
My understanding is that the in_ keyword argument to pack/grid should allow me to specify the managing widget. I want to pack arbitrary widgets inside a Frame subclass, so I passed the widgets and packed them during intialization, but the widgets didn't appear (although space in the window appears to have been allocated...). If I create the widget internally using master which is root, there is no issue and the widgets are displayed as expected.
The following working example and its output demonstrate the issue:
import tkinter as tk
from tkinter import ttk
class ItemContainerExternal(ttk.Frame):
def __init__(self, master, input_label, input_object):
ttk.Frame.__init__(self, master)
self.label = input_label
self.label.pack(side=tk.LEFT, padx=5, pady=3, fill=tk.X, in_=self)
self.input_object = input_object
self.input_object.pack(side=tk.LEFT, padx=5, pady=3, fill=tk.X, in_=self)
def get(self):
return variable.get()
class ItemContainerInternal(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
ttk.Label(master, text='internal').pack(side=tk.LEFT, padx=5, pady=3, fill=tk.X, in_=self)
self.input_object = ttk.Entry(master)
self.input_object.pack(side=tk.LEFT, padx=5, pady=3, fill=tk.X, in_=self)
def get(self):
return variable.get()
if __name__ == '__main__':
root = tk.Tk()
inputobj = ttk.Entry(root)
inputlabel = ttk.Label(root, text='external')
ItemContainerExternal(root, inputlabel, inputobj).grid(row=0, column=0)
ItemContainerInternal(root).grid(row=1, column=0)
root.mainloop()
The problem is that you're creating the entry and label before you're creating the frame, so they have a lower stacking order. That means the frame will be on top of the entry and label and thus, obscuring them from view.
A simple fix is to call lift() on the entry and label:
class ItemContainerExternal(tk.Frame):
def __init__(self, master, input_label, input_object):
...
self.input_object.lift()
self.label.lift()
The order in which widgets get created matters. Newer widgets are "on top of" previous widgets.
Call .lower() on the Frame after you create it, assuming it's created after all the widgets that you will pack into it. If not, you'll need to either call .lower() again on the Frame after creating a new widget to go inside it, or you'll have to raise the new widget via .lift() as per Bryan's answer.
this is a View and Controller part of a program that I am intending writing. My question is why I can't see my grid. My suspicion is that I am not inheriting correctly.
I think the problem is happening here:
"self.frame=Small_Frame(self)"
This is what I understand from my code. class Controller is inheriting from tk. class View is inheriting from tk.Frame. Up to here everything works.
class Small_Frame is my customer widget. The grid is just 12 instances of class Small_Frame using grid() method. I don't know why is it not showing up. Please help me understand. thank you.
import tkinter as tk
class View(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, bg= "yellow", bd =2, relief = tk.RIDGE)
self.parent = parent
self.controller = controller
self.pack(fill=tk.BOTH, expand=1)
for r in range(3):
self.rowconfigure(r, weight=1)
for c in range(4):
self.columnconfigure(c, weight=1)
self.frame=Small_Frame(self)
self.frame.grid(row = r, column = c, padx=1, pady = 1, sticky=
(tk.N, tk.S, tk.W, tk.E))
class Small_Frame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, borderwidth=1, relief="groove")
self.parent = parent
self.pack(fill=tk.BOTH, expand=1)
class Controller():
def __init__(self):
self.root = tk.Tk()
self.view = View(self.root, self)
self.root.title("notbook my own try")
self.root.geometry("1200x650")
self.root.config(bg="LightBlue4")
self.root.mainloop()
if __name__ == "__main__":
c = Controller()
The problem is that you are mixing pack and grid with widgets that share a common parent.
First, you're creating a View object as a child of the root window, and you're calling pack to add it to the root window.
Next, you are creating a series of Small_Frame instances, but you are neglecting to pass the parent to the __init__ of the superclass so these instances become a child of the root window. The instance calls pack on itself, and then you call grid on the instance. Calling grid on the instance causes tkinter to get into an infinite loop as both grid and pack try to resize the parent in different ways. Each one triggers a redraw by the other one.
There are two things you need to do. First, remove self.pack(fill=tk.BOTH, expand=1) from the __init__ of Small_Frame. It's a bad practice to have a class call pack or grid on itself. The code that creates a widget should be responsible for adding it to the screen.
Second, you need to pass parent to __init__ method of the superclass in Small_Frame so that Small_Frame is a child of the correct parent. Your __init__ thus should look like this:
class Small_Frame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, borderwidth=1, relief="groove")
self.parent = parent
I am currently writing a tkinter GUI app using Python 3. I have several frames in my application which should have the same navigation bar(some button widgets and some Label widgets packed in a LabelFrame widget). I want to write this code in a function and call it instead of writing it to every frame and having to change every frame every time I change something in the navigation bar.
I tried putting all of the widgets in a function and calling it just as I said above but it didn't work because I wrote every frame as a class and when I call the function, it doesn't understand where I want to put the widgets to.I pass self as the first argument for creating the widget to place it in the main frame but when I call it in a function, it can't find what self is.
I am looking for any possible way to "teach" the function self or another way to write the navigation bar only once and make any modifications there.
(I think writing the tkinter GUI by writing frames as class has a specific name but I can't recall it right now)
EDIT: Based on a comment here is a example of what I want to do;
(Example below is written without considering the fact it is not possible to use pack with grid. Any other improvements to the code are welcome.)
from tkinter import ttk
import tkinter as tk
#lots of other imports here, they are not related to the question.
def nav_bar():
navLabelFrame=tk.LabelFrame(self)
button=ttk.Button(navLabelFrame,text="I am a button",
command=lambda:controller.show_frame(Page1))
#Other buttons and labels
#...
class app(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Hello World")#TITLE OF THE WINDOW
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = False)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in:(Page1,Page2,Page3,
Page4,Page5,Page6):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(UserLogin)#SET HOME PAGE
def show_frame(self, cont):#FUNCTION TO SWITCH PAGES
frame = self.frames[cont]
frame.tkraise()
class Page1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
Page1.grid(self)
nav_bar()#place the contents of the navbar
#place other stuff here
class Page2(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
Page1.grid(self)
nav_bar()#place the contents of the navbar
#place other stuff here
class Page3(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
Page1.grid(self)
nav_bar()#place the contents of the navbar
#place other stuff here
GUI=app()
GUI.mainloop()
Im trying to teach my self how to use tkinter and I found a useful code through youtube that I don't really fully understand. Would appreciate it if some could help me understand it. Marked the things I did not understand with # ... **.
import tkinter as tk # why not from tkinter import? **
class SampleApp(tk.Tk): # why tk.TK **
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self) # **
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(container, self) # **
self.frames[page_name] = frame # **
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise() # **
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent) # **
self.controller = controller # **
label = tk.Label(self, text="This is the start page",
font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
import tkinter as tk # why not from tkinter import? **
Why not from tkinter import *? Because that is the wrong way to do it. Global imports are bad. Tkinter tutorials tend to do it the wrong way for some reason that I don't understand.
The reason for the as tk part is so that you can do tk.Frame rather than tkinter.Frame, making the code a little easier to type and a little easier to read. It's completely optional.
class SampleApp(tk.Tk):
tk is the name of the tkinter module that was imported. Tk is the name of a class in that module that represents the root window. Every tkinter application must have a single root window. By placing it inside of SampleApp, this creates a subclass of this widget -- a copy that has additional features.
It's not necessary to inherit from tk.Tk. You can inherit from tk.Frame, any other tkinter widget, or even object. It's a personal preference. The choice makes some things easier, some things harder.
container = tk.Frame(self)
The above creates an instance of a Frame widget, which will be used as a container for other "pages". These "pages" will all be stacked on top of each other in this container.
frame = F(container, self)
F is the loop variable. The loop is iterating over a list of classes, so each time through the loop F will be representing a class. F(...) creates an instance of the class. These classes (StartPage, PageOne, PageTwo) all require two parameters: a widget that will be the parent of this class, and an object that will server as a controller (a term borrowed from the UI patter model/view/controller).
The line of code creates an instance of the class (which itself is a subclass of a Frame widget), and temporarily assigns the frame to the local variable frame.
By passing self as the second ("controller") parameter, these new class instances will be able to call methods in the SampleApp class object.
This saves a reference to the just-created frame in a dictionary. The key to the dictionary is the page name (or more accurately, the name of the class).
This is how the show_frame method can determine the actual page widget just from the name of the class.
Creating the frames in a loop is functionally equivalent to the following:
f1 = StartPage(container, self)
f2 = PageOne(container, self)
f3 = PageTwo(container, self)
f1.grid(row=0, column=0, sticky="nsew")
f2.grid(row=0, column=0, sticky="nsew")
f3.grid(row=0, column=0, sticky="nsew")
self.frames = {"StartPage": f1, "PageOne": f2, "PageTwo": f3}
frame.tkraise()
In nearly all GUI toolkits -- tkinter included -- there is the notion of a "stacking order": the order in which things are stacked. Some toolkits might call this the z-order. If two or more widgets are stacked on top of each other (which this code does by putting all pages in the same row and column), the widget that is on the top of the stack is the widget that will typically be visible.
tkraise is a method of a Frame object that will raise the frame to the top of the stacking order. In this line of code, frame refers to one particular instance of one of the pages.
tk.Frame.__init__(self, parent)
Because each page is a subclass of a tk.Frame class, this calls the constructor of the parent class. This is necessary to initialize all of the internal structures that make up the actual frame widget. Although a Frame can take many options, this code chooses to send in only one -- a reference to another widget which is to act as the parent of this new widget.
self.controller = controller
The above code is simply "remembering" the value of the controller variable which was passed in. In this case, the controller is the application. By saving it off, this class can call methods on the SampleApp object.
Note: the code in the question came from a tutorial that copied code from this answer: https://stackoverflow.com/a/7557028/7432. I am the author of that original code, but not the author of the tutorial. In that original answer are links to other questions related to this code.