Python Forum
[Tkinter] how to input a random entry with each button press? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] how to input a random entry with each button press? (/thread-19182.html)



how to input a random entry with each button press? - nadavrock - Jun-17-2019

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)



RE: how to input a random entry with each button press? - Yoriz - Jun-17-2019

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)
...