Code example for setting the title of a root window in Python’s tkinter

To ensure a clean program closure, it is possible to delete the main window when there are no active windows. One approach is to use Toplevel instead of creating a new root. Another solution involves passing the object to the function and using it to set the geometry of the window directly. While agreeing with fhdrsdg’s solution, a slight modification can also be made.


Solution 1:

Examine the reference to the parent root to verify its functionality.

I made clarifications in the code and figure to indicate the locations where colors are assigned after making the necessary edits.

from Tkinter import *
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.parent = master
        self.initUI()
    def initUI(self):
        self.outputBox = Text(self.parent, bg='yellow', height= 10, fg='green', relief=SUNKEN, yscrollcommand='TRUE')
        self.outputBox.pack(fill='both', expand=True)
        self.button1 = Button(self.parent, text='button1', width=20, bg ='blue', fg='green', activebackground='black', activeforeground='green')
        self.button1.pack(side=RIGHT, padx=5, pady=5)
        self.button2 = Button(self.parent, text='button2', width=25, bg='white', fg='green', activebackground='black', activeforeground='green')
        self.button2.pack(side=LEFT, padx=5, pady=5)
def main():
    root = Tk()
    app = Application(root)
    app.parent.geometry('300x200+100+100')
    app.parent.configure(background = 'red')
    app.mainloop()
main()


Solution 2:


In the .configure line, use ‘bg’ instead of typing out ‘background’.

Frequently Asked Questions