0
from tkinter import *
import random

#create root window
root = Tk()

#variables
roll = StringVar(root, name = "roll")

#button script
def clicked():
    x = str(random.randint(1,6))
    root.setvar(name = "roll", value = x)

#button
btn = Button(root, text = "Roll!", fg = "red", bg = "#2596be",
             command = clicked(), height = 5, width = 10,
             font = buttonFontTuple)
btn.pack()

#label
lbl = Label(root, text="You rolled a " + root.getvar(name = "roll"),
            anchor="center", bg="orange", fg="#008080", font=fontTuple,
            borderwidth="1")
lbl.pack(ipadx=0, ipady=10)

This code creates a button and label. The button is meant to change x to a random number and then it will display in the label, however, each time I press the button nothing appears to happen. The number changes every time the code is run though.

1 Answers1

0

The command argument for Button expects a function. When you write clicked() you call the function once, and command gets what your function returns (which is None), so when you click on the button, the command that is executed is None, so nothing happens.

What you want is to pass the function instead, not call it:

btn = Button(root, text = "Roll!", fg = "red", bg = "#2596be",
             command = clicked, height = 5, width = 10,
             font = buttonFontTuple)

Since you call the function once (when the button is created), you see a number, different every time you start the code though, so that's why the code behaves this way

Florent Monin
  • 1,278
  • 1
  • 3
  • 16