I had this error message that can’t be resolved while trying to code using turtle and random.
Exception in Tkinter callback
Traceback (most recent call last):
File “C:\Users\Anh\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py”, line 1921, in call
return self.func(*args)
File “C:\Users\Anh\AppData\Local\Programs\Python\Python310\lib\turtle.py”, line 685, in eventfun
fun()
File “C:\Users\Anh\Desktop\Programs\Python File\e.py”, line 408, in explosion
fy = random.randint(posy – 3, posx + 3)
File “C:\Users\Anh\AppData\Local\Programs\Python\Python310\lib\random.py”, line 370, in randint
return self.randrange(a, b+1)
File “C:\Users\Anh\AppData\Local\Programs\Python\Python310\lib\random.py”, line 353, in randrange
raise ValueError(“empty range for randrange() (%d, %d, %d)” % (istart, istop, width))
ValueError: empty range for randrange() (204, 30, -174)
The code that seemed to cause this error message is:
def explosion():
#Blast
posx = random.randrange(-500, 500)
posy = random.randrange(100, 300)
b.penup()
b.pensize(4)
b.setheading(360)
b.setpos(posx, posy-10)
b.pendown()
b.begin_fill()
for x in range(4):
b.circle(10, 90)
b.end_fill()
time.sleep(0.5)
b.clear()
#Fire
for x in range(random.randrange(3, 6)):
fx = random.randint(posx - 3, posx + 3)
fy = random.randint(posy - 3, posx + 3)
f.penup()
f.pensize(4)
f.setheading(360)
f.setpos(fx, fy-6)
f.pendown()
f.begin_fill()
for y in range(4):
f.circle(6, 90)
f.end_fill()
time.sleep(0.7)
f.clear()
I’ve set this function to onkey() function, and the error code seemed to appear at random times. I’ve tried to reverse posx – 3 and posx + 3, but it didn’t help either.
Please share a runnable minimal reproducible example. Your error says
random.randint(posy - 3, posx + 3)
so that’s probably being called withb
<a
. Canonical: Random module not working. ValueError: empty range for randrange() (1,1, 0)Simple typo:
fy = random.randint(posy - 3, posx + 3)
should befy = random.randint(posy - 3, posy + 3)
(the second term should be in terms ofposy
, notposx
).@ShadowRanger Thank you! That seemed to be the problem, apparently changing posx to posy fixed the entire thing!