Reputation: 83
So, i'm trying to create a program that creates a random number (using randint) to an entry field, when a button is pressed. But I can't figure out how to do it.
import tkinter
from tkinter import Entry, END, E
from random import randint
root = tkinter.Tk()
root.title('Number Generator')
e = Entry(root, font=("LEMON MILK Bold", 24), width=15, borderwidth=10)
e.grid(row=0, column=0, columnspan=3, padx=50, pady=50)
e.delete(0, END)
e.insert(0, number)
number=print(randint(0, 100))
#Definitions
def button_generate():
print(number)
#Buttons
button_generate = tkinter.Button(root, text="Random number", font=("LEMON MILK Bold", 24), padx=10,
pady=10, command=button_generate)
button_exit = tkinter.Button(root, text="Exit", font=("LEMON MILK Bold", 14), padx=5, pady=5,
command=root.quit)
#Grid
button_generate.grid(row=1, column=0, columnspan=3)
button_exit.grid(row=2, column=2, sticky=E)
root.mainloop()
So basically how can I make the random number print into the entry field? (Right now it is not printing anywhere due to my bad code)
Upvotes: 1
Views: 689
Reputation: 11
I like Karthik's solution! It's straight to the point. It suited half my needs, but not 100% because I wanted to copy the text from 'e' to my clipboard (after pressing a different button). Thanks to Karthik, I was able to accomplish this by doing the following:
from tkinter import *
from random import randint
import pyperclip as pc
def get_text():
number = e.get()
if len(e.get()) != 0:
pc.copy(number)
print(f"Number is: '{number}'\nIt is now copied to your clipboard!")
else:
print("There's nothing to copy!")
def set_text():
number = randint(0, 100)
e.delete(0, END)
e.insert(0, number)
print(number)
win = Tk()
e = Entry(win, width = 10)
e.pack()
b1 = Button(win, text = "Gen", command = set_text)
b1.pack()
b2 = Button(win, text = "Get", command = get_text)
b2.pack()
win.mainloop()
Please note that I am using a 3rd party module for the copy functionality.
Upvotes: 0
Reputation: 2431
Please check this out
from tkinter import *
from random import randint
def set_text():
number=randint(0, 100)
e.delete(0,END)
e.insert(0,number)
print(number)
win = Tk()
e = Entry(win,width=10)
e.pack()
b1 = Button(win,text="Gen",command=set_text)
b1.pack()
win.mainloop()
Upvotes: 1