A
A
Arwonk2018-07-10 18:59:22
Python
Arwonk, 2018-07-10 18:59:22

What's wrong with the number generator?

Hello everyone, I just now registered on the toaster, and I want to ask experienced people for help.
I have a working random number generator, here is its code:

from tkinter import *
import random
h = random.randint(1,100)
r = str(h)
tk = Tk()
b = Button(text = "Сгенерировать")
l = Label (width = 20, bg = 'black', fg = "white")
def randomiz(event):
    l["text"]=' '.join(r)
b.bind ("<Button-1>", randomiz)
b.pack()
l.pack()
tk.mainloop()

But there is a problem, I can only press the "Generate" button once - after that, the value does not change, because the random number was snagged in advance and does not loop.
I tried to shove the function randomly into def, it turned out like this:
from tkinter import *
import random
tk = Tk()
b = Button(text = "Сгенерировать")
l = Label (width = 20, bg = 'black', fg = "white")
def randomize(event):
  r = random.randint(1,100)
  s = str(r)
        l["text"] = "".join(s)
b.bind ("<Button-1>", randomize)
b.pack()
l.pack()
tk.mainloop()

But now it gives an error on line 9 (l["text"] = "".join(s)), why is that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lander, 2018-07-10
@usdglander

random.randint(1,100)
Should only be called once per process.

M
Maxim Nevzorov, 2018-07-12
@fixator10

But now it gives an error on line 9 (l["text"] = "".join(s)), why is that?

Because there is an extra indent
from tkinter import *
import random
tk = Tk()
b = Button(text = "Сгенерировать")
l = Label (width = 20, bg = 'black', fg = "white")
def randomize(event):
    r = random.randint(1,100)
    s = str(r)
    l["text"] = "".join(s)
b.bind ("<Button-1>", randomize)
b.pack()
l.pack()
tk.mainloop()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question