简体   繁体   中英

Printing random numbers in tkinter (python3)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM