-1

I'm playing around with TKinter trying to make a number generator.

I can't figure out why a new number doesn't get generated when I use this code:

roll = Button(window, text = 'Roll!', command = num())

But it works if I remove the brackets:

roll = Button(window, text = 'Roll!', command = num)

Thanks guys!

Rest of the code:

from tkinter import *
import random

def num():
    number = random.randint(1, 6)
    num1.configure(text = number)
    return

window = Tk()
window.geometry('300x200')
window.title('Dice')

num1 = Label(window, text = 0)
num1.grid(column = 0, row = 0)

roll = Button(window, text = 'Roll!', command = num)
roll.grid(column = 0, row = 1)

window.mainloop()

1 Answers1

2

When you write num() with the parentheses, you're calling the function immediately, and passing its return value as the argument to Button. When you just name the function, you're passing the function object itself as the argument to Button, and it will call the function later (when the button is clicked).

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Just to make sure I understand. When using the brackets, the random value is defined and set to equal the value of the button and can't be changed until the program is restarted (i.e. the function doesn't get replayed when button is pressed). But without brackets the function will be 'replayed' so a new number generates? – Kernel Pource Jan 02 '20 at 21:28
  • 1
    Yes, the `command` argument to `Button` is expected to be a function. When the button is clicked, it will be called. If you use `num()` with parentheses, you're not passing a function, but rather `None` since that's the function's return value. The function runs only once in that case, before the button is created. – Blckknght Jan 02 '20 at 21:31
  • Appreciate the help Blckknght. I get it now – Kernel Pource Jan 02 '20 at 21:44