简体   繁体   中英

trouble figuring out how to open a new window in tkinter “attribute error”

I am a beginner programmer and want to open a new window after a bottom in clicked in tkinter. I looked online and tried some things but I don't really understand it and keep getting errors. Here is the error I get now.

File "C:\Python33\lib\tkinter\__init__.py", line 2046, in _setup
    self.tk = master.tk
AttributeError: 'App' object has no attribute 'tk'

Here is my code

from tkinter import *
import random

player_dice = []

class App:

    def __init__(self, master):

        for i in range(1,6):
            x = random.randint(1,6)
            player_dice.append(x)
            self.label = Label(master, text = x , fg = "red").grid(row =0, column =i+1)

        self.label = Label(master, text = "Dice:" , fg = "red").grid(row =0, column =1)

        self.hi_one = Button(master, text="one", command=self.say_one).grid(row = 1, column = 1)



    def say_one(self):
        print ("1")
        window = Toplevel(self)
        self.label = Label(window, text = "you selected one" , fg = "red").grid(row =3, column =3)


root = Tk()

app = App(root)

root.mainloop()

thanks for your help

Pass root , not self when call Toplevel : Toplevel(root) . Or omit argument: Toplevel()

from tkinter import *
import random

player_dice = []

class App:
    def __init__(self, master):
        for i in range(1,6):
            x = random.randint(1,6)
            player_dice.append(x)
            self.label = Label(master, text = x , fg = "red").grid(row =0, column =i+1)
        self.label = Label(master, text = "Dice:" , fg = "red").grid(row =0, column =1)
        self.hi_one = Button(master, text="one", command=self.say_one).grid(row = 1, column = 1)

    def say_one(self):
        print ("1")
        window = Toplevel(root) # self -> root
        self.label = Label(window, text = "you selected one" , fg = "red").grid(row =3, column =3)

root = Tk()
app = App(root)
root.mainloop()

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