Creating multiple widgets within a class frame - python

In simply trying to work on organizing my code, I've found online that it seems to be best to put much of your code into classes when needed. So in doing that, I'd figure that I'll try to create a frame class with create_labels and create_buttons methods.
My goal is to be able to create 2 or more seperate frames that are similar in style (hence why I find it best to make a frame class). Then, using methods, create labels, buttons, and other widgets and allow them to move around with ease within their respective frames.
So here's my code:
import tkinter as tk
window = tk.Tk()
class MyFrame(tk.Frame):
def __init__(self, parent, **kwargs):
tk.Frame.__init__(self, parent)
self.parent = parent
self.layout(**kwargs)
def labels(self, text, **kwargs):
tk.Label.__init__(self, text=text)
self.layout(**kwargs)
def buttons(self, text, command, **kwargs):
tk.Button.__init__(self, text=text, command=command)
self.layout(**kwargs)
def layout(self, row=0, column=0, columnspan=None, row_weight=None, column_weight=None, color=None, sticky=None, ipadx=None, padx=None, ipady=None, pady=None):
self.grid(row=row, column=column, columnspan=columnspan, sticky=sticky, ipadx=ipadx, padx=padx, ipady=ipady, pady=pady)
self.grid_rowconfigure(row, weight=row_weight)
self.grid_columnconfigure(column, weight=column_weight)
self.config(bg=color)
frame_1 = MyFrame(window, row=0, column=0, sticky="news", color="pink")
frame_1.buttons("Btn_1/Frme_1", quit, row=0, column=0)
frame_1.buttons("Btn_2/Frme_1", quit, row=0, column=1)
frame_2 = MyFrame(window, row=1, column=0, sticky="news", color="green")
frame_2.buttons("Btn_1/Frme_2", quit, row=0, column=0)
frame_2.buttons("Btn_2/Frme_2", quit, row=0, column=1)
window.grid_columnconfigure(0, weight=1)
window.grid_columnconfigure(1, weight=1)
window.grid_rowconfigure(1, weight=1)
window.grid_rowconfigure(0, weight=1)
window.mainloop()
Now I think a problem of mine is during the __init__ method because there should be 2 frames and 2 buttons per frame. However, there's no errors which makes it harder to find out for sure of that's why only the latest buttons and frames exist. I don't even think it's a case of one frame or widget 'covering' another. I think the second frame/widgets seem to be overwriting the first frame/widgets.
Any help is appreciated.

The issue lies with your layout function. Both the frames are being grided on the row=0 and column=0, as you are not passing any specific row and column to the function. Hence, the overwriting of the frames can be seen.
Another issue (possible) in your code is that the frame_1 and frame_2 buttons do not belong to the Frame widget but to the root window

Related

Scrollable Tkinter GUI with shiftable pods

I am trying to make a GUI such as this with pods, each containing their own elements such as text, images and buttons.
My goal is to make it so that the so called pods can be added to the GUI window (a scrolling capable window) at any point in the code and updated in the window shifting the previous pod to the right or down to the next row if the current row is full like the image below.
I have never messed with Tkinter before so I was wondering if anyone could help me with what steps I would need to take to make such a GUI.
Implement a class that inherits from the Frame class. You can then create as many instances of this class that you want. Since you want the pods to wrap, you can use a Text widget to hold the pods since it's the only scrollable widget that natively supports wrapping.
The "pod" class might look something like this:
class Pod(tk.Frame):
def __init__(self, parent, title, subtitle, image):
super().__init__(parent, bd=2, relief="groove")
if isinstance(image, tk.PhotoImage):
self.image = image
else:
self.image = tk.PhotoImage(file=image_path)
self.title = tk.Label(self, text=title)
self.image_label = tk.Label(self, image=self.image, bd=1, relief="solid")
self.subtitle = tk.Label(self, text=subtitle)
self.b1 = tk.Button(self, text="Button 1")
self.b2 = tk.Button(self, text="Button 2")
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure((0,1), weight=1)
self.title.grid(row=0, column=0, columnspan=2, sticky="ew")
self.image_label.grid(row=1, column=0, columnspan=2, sticky="nsew", padx=8, pady=8)
self.subtitle.grid(row=2, column=0, columnspan=2, sticky="ew")
self.b1.grid(row=3, column=0)
self.b2.grid(row=3, column=1)
You can create another class to manage these objects. If you base it on a Text widget you get the wrapping behavior for free. Though, you could also base it on a Frame or Canvas and manage the wrapping yourself.
It might look something like this:
class PodManager(tk.Text):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.configure(state="disabled", wrap="char")
self.pods = []
def add(self, pod):
self.pods.append(pod)
self.configure(state="normal")
self.window_create("end", window=pod)
self.configure(state="disabled")
To tie it all together, create one PodManager class, then pass one or more instances of Pod to its add method:
import tkinter as tk
...
root = tk.Tk()
pm = PodManager(root)
vsb = tk.Scrollbar(root, orient="vertical", command=pm.yview)
pm.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
pm.pack(side="left", fill="both", expand=True)
for i in range(10):
image = tk.PhotoImage(width=200,height=100)
pod = Pod(pm, f"Title #{i+1}", "More Text", image)
pm.add(pod)
root.mainloop()

why isn't my frame stretch completely in tkinter

I tried to stretch the frame using sticky='nsew' but it's not working properly. I have attached the screenshot here.
the white color window is my frame and i want to stick to all corners. i dont wanna mess up with the buttons that i made. its working if i set row=0 but in that case i lost the buttons.. i wanna keep that button too
from tkinter import *
root=Tk()
root.title("manage your cashflow")
#for setting full screen window
screen_width=root.winfo_screenwidth()
screen_height=root.winfo_screenheight()
print(screen_height, screen_width)
root.geometry("%dx%d" % (screen_width,screen_height))
root.configure(bg='grey')
#configure
Grid.rowconfigure(root,0,weight=1)
Grid.columnconfigure(root,0,weight=1)
Grid.columnconfigure(root,1,weight=1)
# creating tabs
up_button1= Button(root, text="the list of month", bg='#ebca87')
up_button1.grid(row=0,column=0, sticky='NEW')
up_button2=Button(root, text="the new month",bg='#ebca87')
up_button2.grid(row=0,column=1,sticky='NEW',pady=0)
#class for frames
class frame:
#method for
def frame2(self):
#for frame sticky
Grid.rowconfigure(root,1,weight=1)
Grid.columnconfigure(root,0,weight=1)
Grid.columnconfigure(root,1,weight=1)
#frame for listbox
frame2=Frame(root)
frame2.grid(row=1,column=0,columnspan=2,sticky="NSEW")
Grid.rowconfigure(frame2,0,weight=1)
Grid.columnconfigure(frame2,0,weight=1)
Grid.columnconfigure(frame2,1,weight=1)
salary_text=Label(frame2,text="salary")
salary_text.pack()
salary_entry=Entry(frame2)
salary_entry.pack()
frame_ob=frame()
frame_ob.frame2()
root.mainloop()
I want to stretch the frame to the buttons. how do I do it?
you guys can see in the screenshot that the white frame doesn't stick to all corners of the 2nd row and 1st and 2 column
Your main issue is Grid.rowconfigure(root,0,weight=1). This is causing the row where the buttons sit to expand at the same rate as the row the frame is in.
Just get rid of that line and it should fix your problem.
That said there are several things I would change with your code.
You use Grid.rowconfigure() and so on and this is not the standard usage. Is there any reason you are doing it this way? Normally I would expect to see frame2.rowconfigure(0, weight=1).
You build your frame as a class but don't actually do anything in it that would require it to be a class. You also do not inherit tk.Frame in your class. I would write it a little different here.
import * is frowned on. It can cause problems when maintaining code over time as it grows and makes it harder to know where the methods are from so trouble shooting can be harder. try import tkinter as tk and use the tk. prefix.
Reasons you might need or want to set a variable name for a widget is if you plan on interacting with it later. Like updating a label or if you want to set a variable name to make it easier to ID what that widget is for. Then you can do that but personally I prefer to avoid setting variables if they will never be modified later.
Your code can be reduced quite a bit.
Here is a non OOP example (I set the frame background to black to make it easier to see if the frame was expanding. You can change this back if you need to):
import tkinter as tk
root = tk.Tk()
root.title("manage your cashflow")
root.geometry("%dx%d" % (root.winfo_screenwidth(), root.winfo_screenheight()))
root.configure(bg='grey')
root.rowconfigure(1, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
tk.Button(root, text="the list of month", bg='#ebca87').grid(row=0, column=0, sticky='NEW')
tk.Button(root, text="the new month", bg='#ebca87').grid(row=0, column=1, sticky='NEW', pady=0)
frame2 = tk.Frame(root, bg='black')
frame2.grid(row=1, column=0, columnspan=2, sticky="NSEW")
frame2.rowconfigure(0, weight=1)
frame2.columnconfigure(0, weight=1)
frame2.columnconfigure(1, weight=1)
tk.Label(frame2, text="salary").pack()
salary_entry = tk.Entry(frame2)
salary_entry.pack()
root.mainloop()
Results:
For a more OOP geared option you can do something like this.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("manage your cashflow")
self.geometry("%dx%d" % (self.winfo_screenwidth(), self.winfo_screenheight()))
self.configure(bg='grey')
self.rowconfigure(1, weight=1)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
tk.Button(self, text="the list of month", bg='#ebca87').grid(row=0, column=0, sticky='NEW')
tk.Button(self, text="the new month", bg='#ebca87').grid(row=0, column=1, sticky='NEW', pady=0)
frame2 = Frame2()
frame2.grid(row=1, column=0, columnspan=2, sticky="NSEW")
class Frame2(tk.Frame):
def __init__(self):
super().__init__(bg='black')
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
tk.Label(self, text="salary").pack()
salary_entry = tk.Entry(self)
salary_entry.pack()
if __name__ == '__main__':
App().mainloop()

Tkinter: Too much space between label and button frame

I'm pretty new to Tkinter and I build a little window with different widgets.
My Code looks like this:
import tkinter as tk
from tkinter import ttk
class Application(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.master.geometry("800x600")
self.master.title("Tkinter Sandbox")
self.master.grid_rowconfigure(0, weight=1)
self.master.grid_columnconfigure(1, weight=1)
self._create_left_frame()
self._create_button_bar()
self._create_label_frame()
def _create_left_frame(self):
frame = tk.Frame(self.master, bg="red")
tree_view = ttk.Treeview(frame)
tree_view.column("#0", stretch=tk.NO)
tree_view.heading("#0", text="Treeview")
tree_view.pack(fill=tk.Y, expand=1)
frame.grid(row=0, column=0, rowspan=2, sticky=tk.N + tk.S)
def _create_button_bar(self):
frame = tk.Frame(self.master, bg="blue")
button_run_single = tk.Button(frame, text="Button 1")
button_run_all = tk.Button(frame, text="Button 2")
button_details = tk.Button(frame, text="Button 3")
button_run_single.grid(row=0, column=0)
button_run_all.grid(row=0, column=1, padx=(35, 35))
button_details.grid(row=0, column=2)
frame.grid(row=0, column=1, sticky=tk.N)
def _create_label_frame(self):
frame = tk.Frame(self.master, bg="blue")
name_label = tk.Label(frame, text="Label 1")
performance_label = tk.Label(frame, text="Label 2")
name_entry = tk.Entry(frame)
performance_entry = tk.Entry(frame)
name_label.grid(row=0, column=0)
name_entry.grid(row=0, column=1)
performance_label.grid(row=1, column=0)
performance_entry.grid(row=1, column=1)
frame.grid(row=1, column=1)
if __name__ == '__main__':
root = tk.Tk()
app = Application(root)
app.mainloop()
Between the three buttons and the label + entry frame is a huge space. I want the button and label + entry frame right under each other, without the huge space but the treeview should also expand vertically over the whole application window.
I think the problem might be my row and column configuration but I don't know how to solve this problem.
The way you've structured your code makes it hard to see the problem. As a good general rule of thumb, all calls to grid or pack for widgets within a single parent should be in one place. Otherwise, you create dependencies between functions that are hard to see and understand.
I recommend having each of your helper functions return the frame rather than calling grid on the frame. That way you give control to Application.__init__ for the layout of the main sections of the window.
For example:
left_frame = self._create_left_frame()
button_bar = self._create_button_bar()
label_frame = self._create_label_frame()
left_frame.pack(side="left", fill="y")
button_bar.pack(side="top", fill="x")
label_frame.pack(side="top", fill="both", expand=True)
I used pack here because it requires less code than grid for this type of layout. However, if you choose to switch to grid, or wish to add more widgets to the root window later, you only have to modify this one function rather than modify the grid calls in multiple functions.
Note: this requires that your functions each do return frame to pass the frame back to the __init__ method. You also need to remove frame.grid from each of your helper functions.
With just that simple change you end up with the button bar and label/entry combinations at the top of the section on the right. In the following screenshot I changed the background of the button_bar to green so you can see that it fills the top of the right side of the UI.
You need to change line
self.master.grid_rowconfigure(0, weight=1)
to
self.master.grid_rowconfigure(1, weight=1)
so that the second row takes all the space. Then you need to stick widgets from the label frame to its top by adding sticky parameter to the grid call in _create_label_frame:
frame.grid(row=1, column=1, sticky=tk.N)
I prefer to use the Pack Function since it gives a more open window - its easy to configure. When you use Pack() you can use labels with no text and just spaces to create a spacer, by doing this you won't run into the problem your facing.

tkinter widgets on one frame affecting another frame alignment

this program works functionality wise so far anyway so that's not my issue. My issue is something to do with how the alignment works for widgets with multiple frames. If I make the widgets on one frame longer width wise, than the other frames, it will center all the frames based on the widest frame rather than each individual frame. The widest frame right now in this code is 'ChangePasswordPage' as it will almost always use a long string for the label; this causes all of the other frames to shift to the left. If I remove the 'sticky="nsew"' from frame.grid(column=0, row=0, sticky="nsew") it will allign everything properly but the frame doesn't fill outwards so you can see the other frames behind each other.
I am not sure how to fix this and would love some help. I have been trying different ways such as unloading each widget and then reloading it but getting errors there too. Any help will be highly appreciated.
Here's my condensed code:
import tkinter as tk
from tkinter import ttk, messagebox
class CCTV(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack()
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (LoginPage, ChangePasswordPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(column=0, row=0, sticky="nsew")
self.creatingAccount()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def creatingAccount(self):
self.show_frame(LoginPage)
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.createView()
def createView(self):
self.labelPassword = ttk.Label(self, text="Password")
self.entryPassword = ttk.Entry(self, show = "*")
self.buttonLogin = ttk.Button(self, text="Login", command=lambda: self.controller.show_frame(ChangePasswordPage))
self.labelPassword.grid(row=2, column=3, sticky="w")
self.entryPassword.grid(row=2, column=4, sticky="e")
self.buttonLogin.grid(row=3, columnspan=6, pady=10)
class ChangePasswordPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.createView()
def createView(self):
self.labelSecurityQuestion = ttk.Label(self, text="A very very very very very very very very very very long string")
self.entrySecurityQuestion = ttk.Entry(self)
self.buttonCreateAccount = ttk.Button(self, text="Change Password", command=lambda: self.controller.show_frame(LoginPage))
self.labelSecurityQuestion.grid(row=3, column=0, sticky="w")
self.entrySecurityQuestion.grid(row=3, column=1, sticky="e")
self.buttonCreateAccount.grid(row=5, columnspan=2, pady=10)
app = CCTV()
app.geometry("800x600")
app.mainloop()
There are usually many ways to solve layout problems. It all depends on what you actually want to do, what actual widgets you're using, and how you expect widgets react when their containing windows or frames change.
When you use grid, by default it gives widgets only as much space as they need. Any extra space within the containing widget will go unused. If you want grid to use all available space you must tell it how to allocate the extra space by giving rows and columns "weight". You are not doing so, so extra space is not being used, and thus, your widgets aren't being centered.
As a rule of thumb, for any container (typically, a Frame) that uses grid, you must give a weight to at least one row, and one column. If you have a canvas or text widget, usually the row and column it is in is the one you want to get the un-allocated space. If you have entry widgets that you want to grow and shrink, you'll often give a weight to the column(s) that contain the entry widgets. Often you'll have multiple rows and/or columns that you want to be given extra space, though there are also times where you want everything centered, with extra space being allocated along the edges.
In your specific case, to center everything in the password screen there are several solutions. I will detail a couple.
Using only grid, and placing all widgets directly on the page
When you want to arrange absolutely all of your widgets in one frame and manage them with grid, and you want everything centered in the window, you can give all of the weight to rows and columns that surround your content.
Here's an example. Notice that the widgets are in rows 1 and 2, and columns 1 and 2, and all extra space is being given to rows 0 and 3, and columns 0 and 3.
def createView(self):
...
self.labelPassword.grid(row=1, column=1, sticky="e")
self.entryPassword.grid(row=1, column=2, sticky="ew")
self.buttonLogin.grid(row=2, column=1, columnspan=2)
self.grid_rowconfigure(0, weight=1)
self.grid_rowconfigure(3, weight=1)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
Using a nested frame
Another approach is to place the widgets into an inner frame that exactly fits its contents. When you do that, you only have to worry about centering that one frame within the "page" since, when you center the frame, by definition everything in the frame will also be centered relative to the window as a whole.
When you do that you can skip worrying about row and column weights because you want the inner frame to shrink to fit the contents and thus not have to worry about un-allocated space. However, I personally think it's good to always give at least one row and one column weight.
Here's an example using the inner frame technique. Notice how the widgets are placed in the inner frame rather than self, and the inner frame uses pack with no options which causes it to be centered at the top of its parent. You could also use place, which is particularly convenient if you want the password prompt centered vertically as well.
def createView(self):
inner_frame = tk.Frame(self)
inner_frame.pack(side="top", fill="none")
self.labelPassword = ttk.Label(inner_frame, text="Password")
self.entryPassword = ttk.Entry(inner_frame, show = "*")
self.buttonLogin = ttk.Button(inner_frame, text="Login", command=lambda: self.controller.show_frame(ChangePasswordPage))
self.labelPassword.grid(row=1, column=1, sticky="e")
self.entryPassword.grid(row=1, column=2, sticky="ew")
self.buttonLogin.grid(row=2, column=1, columnspan=2)
Summary
Layout out widgets requires a methodical approach. It helps to temporarily give each frame a distinct color so that you can see which frames are growing or shrinking to fit their contents and/or their parents. Often times that is enough to see whether the problem is with a frame, the contents in the frame, or the contents in the containing frame.
Also, you should almost never use pack, place or grid without giving explicit arguments. When you use grid, always give at least one row and one column a weight.

How to get an all sticky grid of Treeview and Scrollbar in Python Tkinter?

What I want in Tkinter in Python 2.7 is the following grid layout:
However once, I start using the grid() functions instead of pack() functions, nothing is showing on running the script. The following is what I am stuck with:
import Tkinter, ttk
class App(Tkinter.Frame):
def __init__(self,parent):
Tkinter.Frame.__init__(self, parent, relief=Tkinter.SUNKEN, bd=2)
self.parent = parent
self.grid(row=0, column=0, sticky="nsew")
self.menubar = Tkinter.Menu(self)
try:
self.parent.config(menu=self.menubar)
except AttributeError:
self.tk.call(self.parent, "config", "-menu", self.menubar)
self.tree = ttk.Treeview(self.parent)
self.tree.grid(row=0, column=0, sticky="nsew")
self.yscrollbar = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
self.yscrollbar.grid(row=0, column=1, sticky='nse')
self.tree.configure(yscrollcommand=self.yscrollbar.set)
self.yscrollbar.configure(command=self.tree.yview)
if __name__ == "__main__":
root = Tkinter.Tk()
root.title("MyApp")
app = App(root)
app.pack()
app.mainloop()
Any help will be highly appreciated.
You have several problems that are affecting your layout.
First, some of the widgets inside App use self as the parent, some use self.parent. They should all use self in this particular case. So, the first thing to do is change the parent option of the Treeview to self.
self.tree = ttk.Treeview(self)
Second, since your main code is calling app.pack(), you shouldn't be calling self.grid. Remove the line `self.grid(row=0, column=0, sticky="nsew"). It's redundant.
Third, you are using very unusual code to add the menubar. You need to configure the menu of the root window. There's no need to put this in a try/except block, and there's no reason to use self.tk.call. Simply do this:
self.parent.configure(menu=self.menubar)
This assumes that self.parent is indeed the root window. If you don't want to force that assumption you can use winfo_toplevel() which will always return the top-most window:
self.parent.winfo_toplevel().configure(menu=self.menubar)
Finally, since you are using grid, you need to give at least one row and one column a "weight" so tkinter knows how to allocate extra space (such as when the user resizes a window).
In your case you want to give all of the weight to row and column 0 (zero), since that's where you've placed the widget which needs the most space:
def __init__(self, parent):
...
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
Note: you'll also want to make sure when you call app.pack() that you give it parameters that makes it fill any extra space, too. Otherwise the tree will fill "app", but "app" would not fill the window.
app.pack(fill="both", expand=True)
Here is a fully working example with all of those changes. I grouped the main layout code together since that makes the code easier to visualize and easier to maintain:
import Tkinter, ttk
class App(Tkinter.Frame):
def __init__(self,parent):
Tkinter.Frame.__init__(self, parent, relief=Tkinter.SUNKEN, bd=2)
self.parent = parent
self.menubar = Tkinter.Menu(self)
self.parent.winfo_toplevel().configure(menu=self.menubar)
self.tree = ttk.Treeview(self)
self.yscrollbar = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
self.tree.configure(yscrollcommand=self.yscrollbar.set)
self.tree.grid(row=0, column=0, sticky="nsew")
self.yscrollbar.grid(row=0, column=1, sticky='nse')
self.yscrollbar.configure(command=self.tree.yview)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
if __name__ == "__main__":
root = Tkinter.Tk()
root.title("MyApp")
app = App(root)
app.pack(fill="both", expand=True)
app.mainloop()
Your question mentioned grid, but in this case you could save a few lines of code by using pack. pack excels in layouts like this, where your gui is aligned top-to-bottom and/or left-to-right. All you need to do is replace the last five lines (the calls to grid, grid_rowconfigureandgrid_columnconfigure`) with these two lines:
self.yscrollbar.pack(side="right", fill="y")
self.tree.pack(side="left", fill="both", expand=True)

Categories

Resources