Reputation: 33
I want to write program which draws random number from a list after clicking button. I've written it, but it's doesn't work like I would like to. It's printing the numbers one under the other. It's working like that.
Here's my code:
from tkinter import *
import random
def draw(param):
number = Label(root, height=1, width=20, text=param)
return number.pack()
root = Tk()
frame = Frame(root, width=300, height=450)
frame.pack()
numbers = [x for x in range(1,6)]
buttonDraw = Button(frame, text="Draw",
command=lambda: draw(random.choice(numbers)))
buttonDraw.pack()
root.mainloop()
Is there a way to replace previous first number with new random number after clicking a button?
Upvotes: 0
Views: 191
Reputation: 2022
It's because you're making new tkinter.Label
each time you press a button. Make a tkinter.Label
outside of the draw
method and and only change the value in the draw
method.
from tkinter import *
import random
def draw(param):
num.set(param)
root = Tk()
frame = Frame(root, width=300, height=450)
frame.pack()
numbers = [x for x in range(1, 6)]
buttonDraw = Button(frame, text="Draw",
command=lambda: draw(random.choice(numbers)))
buttonDraw.pack()
num = StringVar()
Label(root, height=1, width=20, textvariable=num).pack()
root.mainloop()
Upvotes: 1