Kevin
Kevin

Reputation: 43

Empty window from class

Why is the window empty? Do I need to use frame? I'm trying to create a frame out of class and put the information in it.

from tkinter import *
from tkinter import ttk

#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")

class userInfo:
    def __init__(self, user):
        message_label1 = Label(text="I'm going to test your knowledge.", 
        font = ("Arial", "25"), padx=40, pady=20)
        nameLabel = Label(root, text="Enter name", font=("Arial", "15"))
        nameEntry = Entry(root)

        message_label1.pack()
        nameLabel.pack()
        nameEntry.pack()

        self.printButton = Button(root, text="Hello", 
        command=self.printMessage)
        self.printButton.pack()

    def printMessage(self):
        print("Hello")

root.mainloop()

Upvotes: 0

Views: 60

Answers (1)

Mike - SMT
Mike - SMT

Reputation: 15226

Why is the window empty?

Because you never call the class in your code. You can solve this by adding a call to the class just above the mainloop.

His you code that works. I also removed the argument "user" from your class because you do not use it anywhere.

from tkinter import *
from tkinter import ttk

#User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")

class userInfo:
    def __init__(self):
        message_label1 = Label(text="I'm going to test your knowledge.", font = ("Arial", "25"), padx=40, pady=20)
        nameLabel = Label(root, text="Enter name", font=("Arial", "15"))
        nameEntry = Entry(root)

        message_label1.pack()
        nameLabel.pack()
        nameEntry.pack()

        self.printButton = Button(root, text="Hello", 
        command=self.printMessage)
        self.printButton.pack()

    def printMessage(self):
        print("Hello")

userInfo()
root.mainloop()

That said if you are going to use a class it might be better to just inherit from Tk() instead of using a basic class.

Here is a class version of your code that inherits from Tk().

import tkinter as tk
from tkinter import ttk


class UserInfo(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Quiz Game")
        tk.Label(self, text="I'm going to test your knowledge.", font = ("Arial", "25"), padx=40, pady=20).pack()
        tk.Label(self, text="Enter name", font=("Arial", "15")).pack()
        self.name_entry = tk.Entry(self)

        self.name_entry.pack()

        tk.Button(self, text="Hello", command=self.print_message).pack()
        tk.Button(self, text="Hello", command=self.new_window).pack()

    def print_message(self):
        print("Hello")

    def new_window(self):
        top = tk.Toplevel(self)
        tk.Label(top, text="Some new window").pack()

UserInfo().mainloop()

Upvotes: 3

Related Questions