Python Forum
[Tkinter] how to input a random entry with each button press?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] how to input a random entry with each button press?
#1
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)
Reply
#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)
...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  .get() invoke after a button nested press iddon5 5 3,218 Mar-29-2021, 03:55 AM
Last Post: deanhystad
  [Tkinter] Button Plays Random .MP3 File From Folder blufacebaby 2 2,045 Feb-05-2021, 02:19 AM
Last Post: BashBedlam
  tkinter touchscreen scrolling - button press makes unwanted scrolling nanok66 1 3,923 Dec-28-2020, 10:00 PM
Last Post: nanok66
  [Tkinter] Getting Input from Tkinter Entry juliabrushett 6 21,218 May-30-2020, 03:29 PM
Last Post: Larz60+
  [Tkinter] Binding Entry box to <Button-3> created in for loop iconit 5 4,876 Apr-22-2020, 05:47 AM
Last Post: iconit
  Anytime I press the button, the result is depicted Jionni 2 2,185 Feb-24-2020, 10:08 AM
Last Post: Jionni
  Transfer Toplevel window entry to root window entry with TKinter HBH 0 4,420 Jan-23-2020, 09:00 PM
Last Post: HBH
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 4,949 Jul-21-2019, 06:02 PM
Last Post: FullOfHelp
  [Tkinter] Not getting entry values on button click & treeview not updating ? swanysto 4 6,960 May-10-2019, 04:16 PM
Last Post: swanysto
  [Tkinter] how to get the entry information using Entry.get() ? SamyPyth 2 3,452 Mar-18-2019, 05:36 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020