So I'm using tkinter to create a button that displays a random item from a list. When pressed, it displays a new item from said list, by looping a random number generator until it creates a number different to the old one. As they're tkinter buttons, the creation of a new number has to be a function, and the button itself is inside a function.
I've found that the variable for the current random number is not refreshing properly. The value is changing globally but not inside the function containing the button, so when said button runs the function to generate a new number, it checks it against the very first number generated, rather than the previous one.
from tkinter import *
import random
global rnum
def Load():
ListPath = (".\\Lists\\test.txt")
f = open(ListPath, "r")
LineList = f.readlines()
rnum = random.randint(0,(LineList.__len__()-1))
load = Tk()
word = Button(load, text = LineList[rnum], command = lambda: NewRN(rnum, word, LineList), font = ("Calibri", 30))
word.pack()
def NewRN(rnum, word, LineList):
rnumold = rnum
while(rnum == rnumold):
rnum = random.randint(0,(LineList.__len__()-1))
word.config(text = LineList[rnum])
return(rnum)
Load()
When pressing the button, there is the chance it will display the same item from the list, as rnum is not being passed back into the function once it is already running.
Does anyone have a solution for this issue? Thanks in advance.