Is there a way to make a label show in every window for tkinter without having to write out every single line of code over and over

Viewed 61

I am wondering if there is a way, in tkinter or using any other python module, to make it so you keep a label or any other element in every window made by just using something like a function that makes the label within the window? I've tried this:

#Modules
import tkinter as tkin

#The initializer window
class Test:
  def __init__(self):
    #Initializes the main window
    self.start = tkin.Tk()
    self.start.title('Test')
    self.label_thing()

  #Makes a label
  def label_thing(self):
    self.label1 = tkin.Label(text='Not Button')
    self.label1.pack()

I don't know if I made any errors or if this isn't a thing you can do but I'd also like to refrain from having the label localized to this window and having to remake the code for every window.

1 Answers

Let us assume you have a button that creates windows, you would pass this window as an argument to the function that creates the label, so like:

import tkinter as tk # Fixed weird import naming

class Test:
    def __init__(self):
        self.start = tk.Tk()
        self.start.title('Test')

        self.label_thing(self.start) # Label on the main window
        
        tk.Button(self.start,text='Click me',command=self.create_win).pack()
        
        self.start.mainloop()

    def label_thing(self, master):
        self.label1 = tk.Label(master, text='Not Button')
        self.label1.pack()

    def create_win(self):
        new = tk.Toplevel()
        self.label_thing(new) # Label on the new window
    
if __name__ == '__main__':
    Test()

As you can see, as long as you press the button, new windows are created, and all those windows have the label on them, dynamically.

Related