October 24, 2024
Chicago 12, Melborne City, USA
python

tkinter, widgets and OOP Placing in windows


Trying to understand how to specify which window will hold which widget.
I am having difficulty with something that seems incredibly basic, but I can’t see it.
The following is from Wikipedia (https://en.wikipedia.org/wiki/Tkinter):

import tkinter as tk

class Application(tk.Frame):

    def __init__(self, root=None):
        tk.Frame.__init__(self, root)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.medialLabel = tk.Label(self, text="Hello World")
        self.medialLabel.config(bg="#00ffff")
        self.medialLabel.grid()
        self.quitButton = tk.Button(self, text="Quit", command=self.quit)
        self.quitButton.grid()

app = Application()
app.root = tk.Tk()
app.root.title('Sample application')
app.mainloop()

My questions:
Why do 2 windows popup? How do I re-write this to have the widgets show in the “Sample application” window? How could I change this to show the label in one window and the button in another using OOP?

I have eliminated “root” from the code: no change in output. Eliminating self.grid() shows 2 empty windows, as does eliminating the function and moving the label & button to the main code. tk.Frame appears to do nothing



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video