Home > Software engineering >  Having trouble with Tkinter
Having trouble with Tkinter

Time:09-27

I just need help in why this code does not work. I am unfamiliar with tkinter and this is the code that I was given and was told it should work. I see it says root is not defined but not sure what it should be defined as because I am assuming root is from tkinter? The only thing is that line 2 is grayed out. If you could help it would be greatly appreciated!

import tkinter as tk

from tkinter import *


class MyFirstGUI:

    def __init__(self):
        root.gui = tk.TK()
        root.gui.title("A simple GUI")
        root.gui.label = tk.Label(text="This is our first GUI!")
        root.label.pack()
        root.greet_button = tk.Button(text="Greet", command=self.greet)
        root.greet_button.pack()
        root.close_button = tk.Button(text="Close", command=self.gui.destroy)
        root.close_button.pack()
    def greet(root):
        print("Greetings!")
root.mainloop()

my_gui = MyFirstGUI()

CodePudding user response:

The identifier root is often assigned from tk.Tk(). If that's the case, then root will be the Tk application and the root of the Tk display graph.

You do all of your setup in the MyFirstGUI class's constructor, but you only use a local variable to keep track of the results. You therefore lose access to all of it when you exit the constructor. I expect that you want to create everything as a root attribute on self so that your setup is encapsulated and preserved by the class.

Here's how I would rework your code to get it to do what I think you intend:

import tkinter as tk
from tkinter import *

class MyFirstGUI:

    def __init__(self):
        self.root = Tk()
        self.root.title("A simple GUI")
        self.root.label = tk.Label(text="This is our first GUI!")
        self.root.label.pack()
        self.root.greet_button = tk.Button(text="Greet", command=self.greet)
        self.root.greet_button.pack()
        self.root.close_button = tk.Button(text="Close", command=self.root.destroy)
        self.root.close_button.pack()

    def greet(root):
        print("Greetings!")

my_gui = MyFirstGUI()
my_gui.root.mainloop()
  • Related