Tkinter widgets into classes.

Christian Gollwitzer auriocus at gmx.de
Sun Feb 2 11:15:21 CET 2014


Am 01.02.14 20:43, schrieb Lewis Wood:
> I was wandering if I could dynamically change my GUI and after a few searches on Google found the grid_remove() function. What I'm wandering now is if there is a way to group a lot of widgets up into one, and then use the one grid_remove function which will remove them all.
>
> Is it possible to do this in a class like this?
>
> class group1:
>      label1=Label(text="Upon clicking the button").grid(row=0,column=0)
>      label2=Label(text="The menu will dynamically change").grid(row=1,column=0)
>
> group1.grid_remove()

Well, you are on the right track, it is a good idea to structure a 
complex GUI by breaking it up into smaller functional pieces. The right 
way to do it is called "megawidget", and it's done by making a Frame 
which contains the subwidgets; e.g.

=========================
import Tkinter as Tk
import ttk

# python3:
# import tkinter as Tk
# from tkinter import ttk

class dbllabel(ttk.Frame):
	def __init__(self, parent, text1, text2):
		ttk.Frame.__init__(self, parent)
		# python3:
		# super(dbllabel, self).__init__(self, parent)
		self.l1=ttk.Label(self, text=text1)
		self.l2=ttk.Label(self, text=text2)
		self.l1.grid(row=0, column=0)
		self.l2.grid(row=1, column=0)


# now use the dbllabel in our program
# like a regular widget
root=Tk.Tk()
mainframe = ttk.Frame(root)
mainframe.pack(expand=True, fill=Tk.BOTH)

# here is no difference between making a button
# and our fresh new megawidget
foo=ttk.Button(mainframe, text="Some other widet")
bar=dbllabel(mainframe, text1="First line", text2="Second line")

foo.grid(row=0, column=0)
bar.grid(row=0, column=1)

root.mainloop()
========================

Note that
1) I only have python2 to test it here now, so there might be an error 
on the python3 parts

2) I've used ttk widgets all over where possible. This should give the 
most expected look and feel on all platforms

3) More complex megawidgets will of course also group functionality 
(i.e. reactions to button clicks etc.) in the same megawidget class

	Christian




More information about the Python-list mailing list