0

I have this python code for make GUI through tkinter.

I'm trying to activate a new form(form2) on the top when I press the button on Form 1.

I developed based on the inheritance of tkinter class.

My code usually works well, but I found one problem.

If I run Form 2 through the button event on Form 1, the font on Form 2 is not changed.

Errors do not occur at all.

enter image description here

but, if I run it right from the main as below, the font will be changed successfully.

if __name__ == '__main__':    
    form2 = Form2()
    form2.mainloop()  # execute GUI

This is my Code:

from tkinter.ttk import *
import tkinter as tk
from tkinter import messagebox
from tkinter import *
import tkinter.font as tkFont

class Form2(tk.Tk):
    def __init__(self):
        super().__init__()  # Inheritance from tkinter class

        self.title("Form2")
        self.geometry("350x600")
        self.resizable(0, 0)

        self.label = tk.Label(self, text='form2',
                          font=tkFont.Font(family="Roboto", size=18))
        self.label.pack()


class Form1(tk.Tk):
    def __init__(self):
        super().__init__()  # Inheritance from tkinter class

        self.title("Form1")
        self.geometry("350x600")
        self.resizable(0, 0)

        # Get Language Data
        self.label = tk.Label(self, text='form1',
                          font=tkFont.Font(family="Roboto", size=18))
        self.label.pack()

        # preferences button design
        self.button: object = tk.Button(self, overrelief="solid", width=10, height=2,
                                    repeatdelay=1000, repeatinterval=100,
                                    text="Preferences",
                                    font=tkFont.Font(family="Roboto", size=9),
                                    command=lambda: self.button_clicked())
        self.button.pack()

    @staticmethod
    def button_clicked():
        form2 = Form2()
        form2.mainloop()


if __name__ == '__main__':
    form1 = Form1()
    form1.mainloop()

Please give me some advice.

  • It is because you have used more than one instance of `Tk()`. Either use `Toplevel` for class `Form2` or specify the parent in `tkFont.Font(self, ...)` inside `Form2.__init__()`. – acw1668 May 27 '21 at 07:14
  • 1
    Does this answer your question? [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – acw1668 May 27 '21 at 07:19

0 Answers0