0

So I am having trouble as to making a changing die piece

For some reason my function (dice_roller) runs before I hit the button, which doesn't make sense to me.

Aren't functions only executed if they have been told to?

import tkinter,random
from tkinter import messagebox
window=tkinter.Tk()
window.title("Aidan's Dice Roller")
canvas = tkinter.Canvas(window, width=900, height=900)
canvas.pack()
canvas.create_rectangle(0,0,900,900, fill='black')
messagebox.showwarning("Dice Roller", "Do you want to proceed?")
dice1 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice1.gif")
dice2 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice2.gif")
dice3 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice3.gif")
dice4 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice4.gif")
dice5 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice5.gif")
dice6 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice6.gif")
dice1 = tkinter.PhotoImage(file="C:\\Users\\2019200\\Desktop\\Dice\\dice1.gif")
canvas.create_image(450, 350, image=dice1)
while True:
    x=random.randint(1,6)
    print(x)
def dice_roller():
    global x
    if x==1:
        canvas.create_image(450, 350, image=dice1)
    elif x==2:
        canvas.create_image(450, 350, image=dice2)
    elif x==3:
        canvas.create_image(450, 350, image=dice3)
    elif x==4:
        canvas.create_image(450, 350, image=dice4)
    elif x==5:
        canvas.create_image(450, 350, image=dice5)
    elif x==6:
        canvas.create_image(450, 350, image=dice6)
    window.update()
dice_button = tkinter.Button(window, text="hit button for die roll",height=10, width=80, command=dice_roller())
dice_button.place(x=160, y=600)
window.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    Possible duplicate of [Why is Button parameter “command” executed when declared?](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) – Bryan Oakley Apr 05 '18 at 12:50

1 Answers1

1

The problem is coming from the line:

dice_button = tkinter.Button(window, text="hit button for die roll",height=10, width=80, command=dice_roller())

You are calling the dice_roller() function instead of assigning it to the tkinter.Button

Here's the fixed line:

dice_button = tkinter.Button(window, text="hit button for die roll",height=10, width=80, command=dice_roller) #Notice the removed brackets

Hope that helps

lyxαl
  • 1,108
  • 1
  • 16
  • 26