Dalton Sanborn Dalton Sanborn - 1 month ago 49
Python Question

random TKinter Dice Roller

#COS 125 Fall 2016 #5
#Dalton Sanborn
import Tkinter
import random
win = Tkinter.Tk()
win.title('Dice Roller')
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()
row1 = Tkinter.Frame(win)
row2 = Tkinter.Frame(win)
d1 = die(1,row1)
d2 = die(1,row1)
d3 = die(1,row1)
d1.display.pack(side="left")
d2.display.pack(side="left")
d3.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 believe I have most of the stuff correct however in the class
DiceRoller
(Which I know isn't complete) we are supposed to use a constructor (
__init__
) I am not quite sure how the constructor should work. I'm trying to have the computer display a window of the three different integers that the dice roll and a button to roll again.

Answer

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.

Comments