tontsa28
tontsa28

Reputation: 83

How can I create a random number between two entry field numbers in python tkinter?

Okay, here is another idiotic question: I have two entry fields and the idea is to insert a random number into a third entry field. I want that the random number comes from between the two entry fields' values. For example: I type in number 1 into the first entry field and a number 10 into the second. As I press the button, I want it to create the random number from between those 1 and 10 and insert it into the third field. (I'm sorry if this is confusing, I tried my best explaining) Here's some code:

import tkinter
from tkinter import Entry, END, E, W
from random import randint, randrange

root = tkinter.Tk()
root.title('Number Generator')

e1 = Entry(root, font=("LEMON MILK Bold", 24), width=10, borderwidth=10)
e1.grid(row=0, column=0, columnspan=3)

e2 = Entry(root, font=("LEMON MILK Bold", 24), width=5, borderwidth=10)
e2.grid(row=1, column=0, columnspan=2, sticky=W)

e3 = Entry(root, font=("LEMON MILK Bold", 24), width=5, borderwidth=10)
e3.grid(row=1, column=1, columnspan=2, sticky=E)

#Definitions

def button_generate():
    e1.delete(0, END)
    e1.insert(randint(e2.get, e3.get))

def button_clear():
    e1.delete(0, END)

#Buttons

button_generate = tkinter.Button(root, text="Random number", font=("LEMON MILK Bold", 28), padx=20, 
pady=10, command=button_generate)
button_clear = tkinter.Button(root, text="Erase", font=("LEMON MILK Bold", 14), padx=22, pady=5, 
command=button_clear)
button_exit = tkinter.Button(root, text="Exit", font=("LEMON MILK Bold", 14), padx=15, pady=5, 
command=root.quit)

#Grid

button_generate.grid(row=2, column=0, columnspan=3)
button_clear.grid(row=3, column=1)
button_exit.grid(row=3, column=2, sticky=E)

root.mainloop()

Upvotes: 2

Views: 544

Answers (2)

Jona
Jona

Reputation: 1288

Your issues are with the insert method. The first argument of the method is the index, you should provide one. The second argument is the string you want to enter. This string is generated by the randint method. This method asks for two integers. You should get the values from e2 and e3 and convert them to integers.

The button_generate function should be :

  def button_generate():
      e1.delete(0, END)
      e1.insert(0,randint(int(e2.get()), int(e3.get())))

Upvotes: 2

Kevin Mayo
Kevin Mayo

Reputation: 1159

  1. e2.get is a method, you wouldn't get the content in the entry.Like jasonharper pointed out in the comment, it should be e2.get().
  2. Also, entry.get() will return a string instead of a number. to generate random number by random.randint, you need to convert it to a number.
  3. entry.insert() need a index argument,you didn't pass that, so the function should be change to:
def button_generate():
    e1.delete(0, END)
    e1.insert(END, randint(int(e2.get()), int(e3.get())))

Upvotes: 1

Related Questions