Python Forum

Full Version: how to input a random entry with each button press?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a tkinter gui wiht buttons. i have a button that enters random values inside a certain entry. i have a randint that a assigns that random value. however once assigend the button press will only use that same value. i want each time to use a differnt value. how to i accomplish this?

code i have:

root = Tk(  )
entry = Entry(root, textvariable = number)
entry_random = str(randint(2, 10))
def entryrandom():
       entry.insert(END, entry_random)
Button(root, text = "random", width = 10, height = 1, command = entryrandom).grid(row=5, column=2)
When asking a question please post a code sample that can be run.
The reason you get the same random number is because randint is only called once before the button is pressed.
The assignment of entry_random needs to be done in the event handler function so it gets a new value when the button is pressed.
...
def entryrandom():
    entry_random = str(randint(2, 10))
    entry.insert(END, entry_random)
...