简体   繁体   中英

How do I open a new window in TKinter, then add buttons to it?

I'm trying to open a new window in Tkinter, then add buttons to it. The new window opens up no problem, but I get an AttributeError when I try to add buttons to it.

Heres my current code:

from tkinter import *
from tkinter.ttk import *
import datetime
import time
import random 
import json 

class MainWindow(Toplevel):
    def __init__(self, master = None):
        super().__init__(master = master)
        self.title("Jarvis")
        self.geometry("500x500")
        label = Label(self, text="Please choose one of the options below")
        label.pack()

        numberGenButton = Button(MainWindow, text="Number Generator")
        numberGenButton.pack()

        timeWindowButton = Button(MainWindow, text="Clock")
        timeWindowButton.pack()

        passwordGeneratorButton = Button(MainWindow, text="Generate a password")
        passwordGeneratorButton.pack()

master = Tk()
master.geometry("500x500")

welcome = Label(text="Welcome to Jarvis")
welcome.pack()

Label(text="Please note closing this window will close Jarvis!").pack()

getStarted = Button(master, text="Get Started")
getStarted.bind("<Button>", lambda e: MainWindow(master))
getStarted.pack()

master.mainloop()

Error:

  File "c:\Program Files\Python38\lib\tkinter\ttk.py", line 612, in __init__
    Widget.__init__(self, master, "ttk::button", kw)
  File "c:\Program Files\Python38\lib\tkinter\ttk.py", line 557, in __init__
    tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "c:\Program Files\Python38\lib\tkinter\__init__.py", line 2561, in __init__
    BaseWidget._setup(self, master, cnf)
  File "c:\Program Files\Python38\lib\tkinter\__init__.py", line 2530, in _setup
    self.tk = master.tk
AttributeError: type object 'MainWindow' has no attribute 'tk'

Any help here would be awesome!

You can't pass a class as the master for another window, like you're doing here:

numberGenButton = Button(MainWindow, text="Number Generator")
timeWindowButton = Button(MainWindow, text="Clock")
passwordGeneratorButton = Button(MainWindow, text="Generate a password")

With the exception of the root widget, every widget needs some other widget as its master. You need to use the instance , which in this case is self :

numberGenButton = Button(self, text="Number Generator")
timeWindowButton = Button(self, text="Clock")
passwordGeneratorButton = Button(self, text="Generate a password")

What I don't understand is your use of master.mainloop() Just mainloop will suffice and to create a new window just do it like this

root = Tk()
window = Tk()

Please correct me if I am misunderstanding the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM