I am looking to override the Tkinter Frame, Button, Lable and Entry widgets to have them creted and packed in the same line of code. (IMO 2 lines to do this and get a reference for the obj is ugly, inefficient and harder to read even if it provides more flexability).
My previous code was this:
def cFrame(self, element, bg="white", borderwidth=0, relief="groove", side=None, padx=0, pady=0, height=0, width=0, expand=0, fill=None, image=None, highlightbackground=None, highlightcolor=None, highlightthickness=0, ipadx=0, ipady=0):
f = self.TkUtil.Frame(element, bg=bg, borderwidth=borderwidth, relief=relief, height=height, width=width, image=image, highlightbackground=highlightbackground, highlightcolor=highlightcolor, highlightthickness=highlightthickness)
f.pack(side=side, padx=padx, pady=pady, ipadx=ipadx, ipady=ipady, expand=expand, fill=fill)
return f
My proposed class would look like this:
class cFrame(Frame):
def __init__(self, master, **kwargs):
Frame.__init__(*(self, master), **kwargs)
self.pack(**kwargs)
The issue with this being **kwargs does not care if the keyword is valid and returns 'bad option -"kwarg"'.
I have tried expanding the function a bit more but I keep having issues:
class cButton(Button):
def __init__(self, master, **kwargs):
Button.__init__(*(self, master))
self.conf(**kwargs)
def conf(self, **kwargs ):
__pk_ops = {}
for k, v in kwargs.items():
try:
self.configure({k:v})
except:
__pk_ops[k] = v
self._pk(__pk_ops)
def _pk(self, __ops):
self.pack(__ops)
In this code, I have to loop through all kwargs before and indervidually configure them which is a lot of wasted time over the 1000's of widgets needed. Additionally, I have issues where self.configure(text="sometext") errors so 'text' is passed through to the self.pack() method because for some magic reason it doesn't like that option in particular (same for compound in this example too).
My end goal is to have x = Frame(root, bg="black") \n x.pack(side=TOP) be replaced with x = cFrame(root, bg="black", side=TOP) without default any of the options like my current code making any changes difficult and any sort of theam almost impossible.
You can create a custom class to override the pack() as below:
def cWidget:
def pack(self, **kw):
super().pack(**kw) # call original pack()
return self # return widget itself
# can do the same for grid() and place()
Then create custom widget class as below:
import tkinter as tk
class cButton(cWidget, tk.Button): pass
# do the same for other widgets you want
Now you can use the custom button class as below:
...
root = tk.Tk()
def clicked():
print('Button clicked')
btn['text'] = 'Clicked' # can use 'btn' to change its text as well
btn = cButton(root, text='Click me!', command=clicked, bg='gold').pack(padx=10, pady=10)
print(f'{btn=}') # here you won't get None
print(isinstance(btn, tk.Button)) # here you get True
...
Note that for Python 3.8+, you can simply use the Walrus Operator (:=):
(btn := tk.Button(root, text='Click me!')).pack(padx=5, pady=5)
I'm trying to build a script for import in my future projects.
That Script should create some tk.Frames in a tk.Frame and let me edit the created ones in a main.
I think, the best way to get there is to create a Holder_frame class and put some nested classes in.
so I could call them in my main with Holder_frame.F1.
I tried a lot of code and I ended up here making me an account.
Anyway here is where Im at:
import tkinter as tk
from tkinter import Frame,Button
class BaseClass(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.pack()
class Holder_frame(tk.Frame):
Names = []
def __init__(self, master, frames=2):
tk.Frame.__init__(self, master)
self.master = master
frame_names = Holder_frame.Names
for i in range(0,frames):
frame_names.append("F"+str(i+1))
print(frame_names)
Holder_frame.factory()
def factory():
print(Holder_frame.Names)
print(type(BaseClass))
for idex,i in enumerate (Holder_frame.Names):
print(i)
class NestedClass(BaseClass):
pass
NestedClass.__name__ = i
NestedClass.__qualname__ = i
if __name__ == "__main__":
root = tk.Tk()
def raise1():
Holder_frame.F1.tkraise()
def raise2():
Holder_frame.F2.tkraise()
holder=Holder_frame(root,frames=2)
holder.grid(row=1,column=0)
b1 = tk.Button(root, text='1', command=raise1)
b1.grid(row=0,column=0)
b2 = tk.Button(root, text='2', command=raise2)
b2.grid(row=0,column=1)
root.mainloop()
Everything works fine, till I try to call a Frame.
(AttributeError 'Holder_frame' object has no attribute 'F1')
I think my problem is the structure but need some help to solve it.
Any suggestions?
If I'm getting it right I think you mean to have some sort of a Base class that has some configuration which a set of frames have in common like for example you want to have 10 frames of 300x400 geometry and of a brown background in common and later having another set of frames with a different configuration, which can be accessed in an organised way. Then I would say you have an interesting way but I would rather use a list or a dictionary anyway.
Here are some approaches to achieve this goal.
Approach 1
In this approach, I've created a function that returns a dictionary with all the frames created and contained in it like in format ({..., 'F20': tkinter.frame, ...})
import tkinter as tk
def get_base_frames(num, master, cnf={}, **kw):
"""
Create list of frames with common configuration options.
Args:
num (int): Number of frames to be created.
master (tk.Misc): Takes tkinter widget or window as a parent for the frames.
cnf (dict): configuration options for all the frames.
kw: configuration options for all the frames.
Return:
Dictionary of frames ({..., 'F20': tkinter.frame, ...}).
"""
return {f'F{n+1}': tk.Frame(master, cnf=cnf, **kw) for n in range(num)}
if __name__ == "__main__":
root = tk.Tk()
frame_holder = get_base_frames(10, root, width=50, height=50, bg='brown')
# Frames can be accessed through their names like so.
print(frame_holder.get('F1'))
Approach 2
Here I've used class and objects. Where I made this class Frames though you can name it anything you want. I also added some important method like cget() and configure(), through these methods once get a value to an option and configure options for all the frames respectively. There are more useful methods like bind() and bind_all() if you need those just modify this class as per your need.
import tkinter as tk
class Frames(object):
def __init__(self, master=None, cnf={}, **kw):
super().__init__()
num = cnf.pop('num', kw.pop('num', 0))
for n in range(num):
self.__setattr__(f'F{n+1}', tk.Frame(master, cnf=cnf, **kw))
def configure(self, cnf={}, **kw):
"""Configure resources of a widget.
The values for resources are specified as keyword
arguments. To get an overview about
the allowed keyword arguments call the method keys.
"""
for frame in self.__dict__:
frame = self.__getattribute__(frame)
if isinstance(frame, tk.Frame):
if not cnf and not kw:
return frame.configure()
frame.configure(cnf=cnf, **kw)
config = configure
def cget(self, key):
"""Return the resource value for a KEY given as string."""
for frame in self.__dict__:
frame = self.__getattribute__(frame)
if isinstance(frame, tk.Frame):
return frame.cget(key)
__getitem__ = cget
if __name__ == "__main__":
root = tk.Tk()
frame_holder = Frames(root, num=10, width=10,
bd=2, relief='sunken', bg='yellow')
# Frames can be accessed through their naems like so.
print(frame_holder.F4)
print(frame_holder['bg'])
frame_holder.config(bg='blue')
print(frame_holder['bg'])
Approach 3
If you want to have differently configured frames contained in one class, where all those frames have some method in common or some attribute in common.
import tkinter as tk
class BaseFrame(tk.Frame):
def __init__(self, master=None, cnf={}, **kw):
super().__init__(master=master, cnf={}, **kw)
def common_function(self):
"""This function will be common in every
frame created through this class."""
# Do something...
class FrameHolder(object):
def __init__(self, master=None, cnf={}, **kw):
kw = tk._cnfmerge((cnf, kw))
num = kw.pop('num', len(kw))
for n in range(num):
name = f'F{n+1}'
cnf = kw.get(name)
self.__setattr__(name, BaseFrame(master, cnf))
if __name__ == "__main__":
root = tk.Tk()
holder = FrameHolder(root,
F1=dict(width=30, height=40, bg='black'),
F2=dict(width=50, height=10, bg='green'),
F3=dict(width=300, height=350, bg='blue'),
F4=dict(width=100, height=100, bg='yellow'),
)
print(holder.F1)
print(holder.__dict__)
Approach 4
This is the approach that OP is trying to achieve.
import tkinter as tk
class BaseClass(tk.Frame):
def __init__(self, master, cnf={}, **kw):
kw = tk._cnfmerge((cnf, kw))
cnf = [(i, kw.pop(i, None))
for i in ('pack', 'grid', 'place') if i in kw]
tk.Frame.__init__(self, master, **kw)
self.master = master
if cnf:
self.__getattribute__(cnf[-1][0])(cnf=cnf[-1][1])
class Container(tk.Frame):
"""Container class which can contain tkinter widgets.
Geometry (pack, grid, place) configuration of widgets
can also be passed as an argument.
For Example:-
>>> Container(root, widget=tk.Button,
B5=dict(width=30, height=40, bg='black',
fg='white', pack=(), text='Button1'),
B6=dict(width=50, height=10, bg='green', text='Button2',
place=dict(relx=0.5, rely=1, anchor='s')))
"""
BaseClass = BaseClass
def __init__(self, master=None, cnf={}, **kw):
kw = tk._cnfmerge((cnf, kw))
wid = kw.pop('widget', tk.Frame)
for name, cnf in kw.items():
geo = [(i, cnf.pop(i, None))
for i in ('pack', 'grid', 'place') if i in cnf]
setattr(Container, name, wid(master, cnf))
if geo:
manager, cnf2 = geo[-1]
widget = getattr(Container, name)
getattr(widget, manager)(cnf=cnf2)
if __name__ == "__main__":
root = tk.Tk()
Container(root, widget=Container.BaseClass,
F1=dict(width=30, height=40, bg='black', relief='sunken',
pack=dict(ipadx=10, ipady=10, fill='both'), bd=5),
F2=dict(width=50, height=10, bg='green',
pack=dict(ipadx=10, ipady=10, fill='both')),
)
Container(root, widget=tk.Button,
B5=dict(width=30, height=40, bg='black',
fg='white', pack={}, text='Button1'),
B6=dict(width=50, height=10, bg='green', text='Button2',
place=dict(relx=0.5, rely=1, anchor='s')),
)
print(Container.__dict__)
root.mainloop()
A lot can be done and can be modified according to one's needs, these are just some approaches that I think will work very well to automate and keep a set of frames in shape and together.
There can be multiple ways to do this or maybe something better and efficient than these, feel free to give suggestions and share something new.
One solution to this problem, I think, as I don't fully understand your question, but this here was my solution:
import tkinter as tk
from tkinter import Frame,Button
class BaseClass(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.pack()
class Holder_frame(tk.Frame):
def __init__(self, master, frames=2):
tk.Frame.__init__(self, master)
self.master = master
self.frame_names = []
for i in range(frames):
Holder_frame.create_frames("F"+str(i+1), self)
#classmethod
def create_frames(cls, name, master):
setattr(cls, name, tk.Frame(master))
if __name__ == "__main__":
root = tk.Tk()
def raise1():
print(type(Holder_frame.F1))
def raise2():
print(type(Holder_frame.F2))
holder=Holder_frame(root,frames=2)
holder.grid(row=1,column=0)
b1 = tk.Button(root, text='1', command=raise1)
b1.grid(row=0,column=0)
b2 = tk.Button(root, text='2', command=raise2)
b2.grid(row=0,column=1)
print(Holder_frame.__dict__.items())
root.mainloop()
The use of setattr allows one to add variables to the class, just like if you were to type a function into the code. This allows you to access frames from outside the class as somewhat of a "global variable"
I used a file to test if it work outside as an imported module too:
# main.py
from nested_class import Holder_frame
import tkinter as tk
root = tk.Tk()
holder=Holder_frame(root,frames=1000)
holder.grid(row=1,column=0)
print(Holder_frame.__dict__.items())
root.mainloop()
I hope this answers your question,
James
EDIT:
After thinking there is, what I think, to be a cleaner system for what you want. With the code from this post one can see that your my written system could be replaced by a ttk.Notebook, and by removing the top bar by using style.layout('TNotebook.Tab', []), one can see that you would get a frame widget that could have frame widgets inside of it:
import tkinter as tk
import tkinter.ttk as ttk
class multiframe_example:
def __init__(self, master):
self.master = master
style = ttk.Style()
style.layout('TNotebook.Tab', [])
notebook = ttk.Notebook(self.master)
notebook.grid(row=0, column=0)
self.master.grid_rowconfigure(0, weight=1)
self.master.grid_columnconfigure(0, weight=1)
tab1 = tk.Frame(self.master, width=500, height=500, background="green")
tab2 = tk.Frame(self.master, width=500, height=500)
tab3 = tk.Frame(self.master, width=500, height=500)
notebook.add(tab1)
notebook.add(tab2)
notebook.add(tab3)
notebook.select(0) # select tab 1
notebook.select(1) # select tab 2
notebook.select(2) # select tab 3
def main():
root = tk.Tk()
root.geometry("500x500")
multiframe_example(root)
root.mainloop()
if __name__ == '__main__':
main()
Hope this code can support you and does as you would like!
Hello I think I have a python tkinter design issue. I have looked on this to structure my code better. I do not want to change the configuration of all my widgets individually and would like to use parent_widget.winfo_children() command that I found from this question.
I am wondering is there a better way to not individually configure the widgets and yet update their font and Style.
Here is my code and the current behavior:
class TabOne(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.tab1_note = ttk.Notebook(self,width=parent.winfo_screenwidth(), height=parent.winfo_screenheight())
tab1_open_observations = ttk.Frame(self.tab1_note)
tab1_closed_observations = ttk.Frame(self.tab1_note)
self.tab1_note.add(tab1_open_observations, text= "Open Projects")
self.tab1_note.add(tab1_closed_observations, text= "Closed/Deferred Projects")
self.tab1_note.pack()
self.tab_two_load(tab1_open_observations)
self.tab_three_load(tab1_closed_observations)
widget_list = []
widget_list.extend(tab1_open_observations.winfo_children())
widget_list.extend(tab1_closed_observations.winfo_children())
for wid in widget_list:
try:
wid.configure(font = 'helvetica 12')
except:
pass
def tab_one_load(self,tab1_refresh_db):
def tab_two_load(self,tab1_open_observations)
class TabTwo(Frame):
class TabThree(Frame):
class MainWindow(Frame):
def __init__(self, window, **kwargs):
Frame.__init__(self, window, **kwargs)
self.load_ui()
def load_ui(self):
self.note = ttk.Notebook(self,width=self.window.winfo_screenwidth()-(2*self.pad), height=self.window.winfo_screenheight()-(2*self.pad))
self.tab1 = TabOne(self.note)
self.tab2 = TabTwo(self.note)
self.tab3 = TabThree(self.note)
self.note.pack()
def main():
window = Tk()
window.title('Productivity Tool')
app = MainWindow(window)
app.pack(side="top", fill="both", expand=True)
window.mainloop()
if __name__ == '__main__':
main()
Current behavior for dependent drop down lists (code below):
The second list does not overlap if I add project_module_dropdown.configure(font='helvetica 12') below every dependent OptionsMenu, Here is more code for the function tab_two_load()
def tab_two_load(self,tab1_open_observations):
def update_modules(a,b,c):
proj_mo_names = [module[0] for module in project_modules]
proj_mod_select.set(proj_mo_names[0])
project_module_dropdown = OptionMenu(tab1_open_observations,proj_mod_select,*proj_mo_names)
project_module_dropdown.configure(font='helvetica 12')
project_module_dropdown.grid(row=2, column=1,padx=10, pady=10)
proj_select = StringVar(tab1_open_observations,value='Default Text')
proj_select.trace('w',update_modules)
proj_mod_select = StringVar(tab1_open_observations,value='Default Text')
proj_mod_select.trace('w',update_teams)
proj_mod_select.trace('w',update_artifacts)
proj_names = [project[1] for project in projects]
proj_select.set(proj_names[0])
project_dropdown = OptionMenu(tab1_open_observations,proj_select,*proj_names)
project_dropdown.grid(row=1,column=1,padx=10,pady=10)
I think the problem is with how I have structured my code but i believe i have compartmentalized the code well but I am open to suggestions. this is not exactly a code review problem. My problem is overlapping drowdowns, but I feel that I have some duplication in my code that I would like to avoid. Any help is great. Thanks.
I would like this as my desired behavior without adding project_module_dropdown.configure(font='helvetica 12'):
class First_Frame(Frame):
def __init__(self,master):
super().__init__(master)
self.grid()
self.widgets()
def widgets(self):
self.commandent1=StringVar()
self.commandent1.set("tutaj bedzie sie pokazywal aktualny status")
self.img=Image.open("database.XPM","r")
self.image_true=ImageTk.PhotoImage(self.img)
self.label=Label(self,image=self.image_true).grid()
self.label2=Label(self,text="twoje gui uzytkownika").grid()
self.widgets_2()
def widgets_2(self):
self.status_text=Label(self,text=self.commandent1.get())
self.entry1=Entry(self)
self.entry1.bind("<Return>",self.update_status)
self.entry1.grid()
self.status_text.grid()
def update_status(self):
self.x=self.entry1.get()
self.commandent1.set(self.x)
You have 2 main reasons your Label (not text) widget is not updating.
Reason 1. You need to handle the event that is being passed to update_status from the binding. To do this just add event or any argument name really you want. I just use event for readability.
def update_status(self, event):
Reason 2. You need to and the less obvious reason here for some is the way you are using your StringVar() on the label widget. Here you are assigning the current text value of the StringVar() only once and never again. To properly use the StringVar() with a label widget you will need to assign the StringVar() to a textvariable argument and not a text argument.
Like this:
Label(self,textvariable=self.commandent1).grid()
Note I took out the image portion of your code as it was irrelevant to the question. Your final code should look something like this:
from tkinter import *
class First_Frame(Frame):
def __init__(self, master):
super().__init__()
self.grid()
self.widgets()
def widgets(self):
self.commandent1 = StringVar()
self.commandent1.set("tutaj bedzie sie pokazywal aktualny status")
Label(self,text="twoje gui uzytkownika").grid()
self.widgets_2()
def widgets_2(self):
self.entry1 = Entry(self)
self.entry1.bind("<Return>", self.update_status)
self.entry1.grid()
Label(self,textvariable=self.commandent1).grid()
def update_status(self, event):
self.commandent1.set(self.entry1.get())
root = Tk()
First_Frame(root)
root.mainloop()
I apologize in advance if this is a stupid simple question, but i am really bad att python classes and can't seem to get it to work!
Here is my code:
from tkinter import *
a = Tk()
class toolsGUI():
def __init__(self, rootWin):
pass
def frame(self):
frame = Frame(rootWin)
frame.configure(bg = 'red')
frame.grid()
def button(self, binding, text):
btn = Button(rootWin, text=text)
btn.configure(bg = 'orange', fg = 'black')
btn.bind('<'+binding+'>')
btn.grid(row=1, sticky = N+S+E)
I simply want the button() or frame() to understand that rootWin is the same as in __init__, in this case rootWin should be variable a, thus placing the button in the Tk() window. After looking around, I understand that this is not the way to do it. Do anyone have another suggestion that might work?
You're pretty close. You are passing a to the toolsGUI initializer which is the right first step. You simply need to save this as an instance variable, then use the variable whenever you need to reference the root window:
def __init__(self, rootWin):
...
self.rootWin = rootWin
...
def frame(self):
frame = Frame(self.rootWin)
...
An alternative is to have toolsGUI inherit from Frame, in which case you can put all of the widgets in the frame instead of the root window. You then need the extra step of putting this frame inside the root window.
class toolsGUI(Frame):
def __init__(self, rootWin):
Frame.__init__(self, rootWin)
def frame(self):
frame = Frame(self)
...
a = Tk()
t = toolsGUI(a)
t.pack(fill="both", expand=True)
a.mainloop()
As a final bit of advice: don't user variables that are the same name as methods if you can avoid it. "frame" is a poor choice of function names. Instead, call it "create_frame" or something, otherwise it could be confused with class Frame and the local variable frame