Search code examples
pythontkinterdice

random TKinter Dice Roller


import Tkinter
import random
win = Tkinter.Tk()
win.title('Dice Roller')

def mainloop():
    class Die:
        def __init__(self,ivalue, parent):
            self.value = ivalue
            self.display = Tkinter.Label(parent,relief='ridge',borderwidth=4, text=str(self.value))
        def roll(self):
            self.value = random.randint(1,6)
            self.display.config(text=str(self.value))
    class diceRoller:    
        def rolldice():
            d1.roll()
            d2.roll()
            d3.roll()
        def __init__(self):
                self.diceList = []
                self.win = Tkinter.Tk("Dice Roller")

                for i in range(3):
                    di = Die(self.win)
                    self.dieList.append(di)
                    rolldice()

    row1 = Tkinter.Frame(win)
    row2 = Tkinter.Frame(win)
    d1.roll.display.pack(side="left")
    d2.roll.display.pack(side="left")
    d3.roll.display.pack(side="left")
    row1.pack()
    rolldice = Tkinter.Button(row2, command=rolldice(), text = "Roll")
    rolldice.pack()
    row2.pack()


 win.mainloop()

I'm having trouble with my python code with Tkinter. I'm trying to get it to produce a window with three buttons that present the numbers rolled on the dice and another that lets me re roll the dice.


Solution

  • The code you have inside class diceRoller under the method rolldice has to be in some method. It cannot just stay in a class. Create a method using def and add that code to it.

    If a name of a method is __init__, it is called a constructor. A constructor is a method that will be called when the object is created (i.e. when you do diceRoller()). You perhaps should put the code, that's now just laying inside diceRoller into such a method/constructor, I don't know (you should know if that's the case).

    Note: In Python we usually write first characters of class names uppercase.