每次使用随机数(python)都有相同的结果

时间:2017-12-06 21:35:18

标签: python python-3.x random tkinter

def gDiceRoll():

    gDiceOptions.destroy()

    global gDiceRoll
    gDiceRoll = Tk()
    gDiceRoll.title("Green Dice Roll")
    gDiceRoll.config(background="#32cd32")

    lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

    play()

    while True:

        outcomeG = random.randint(1, 100)
        lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

        if outcomeG <= 25:

            lbloutcome.config(text="G1", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G1 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G1.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break

        elif outcomeG <= 22:

            lbloutcome.config(text="G2", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G2 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G2.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break        
        #etc

每次运行程序时, ALWAYS 都会出现G1。我试图通过多种方式解决它,但它们只会产生其他问题。 elif G1 <= 25意味着它有25%的机会做G1但它总是做G1。

我该如何解决这个问题?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

让我们说outcomeG <= 22

然后您的代码首先遇到outcomeG <= 25条件,并进入第一个条件,始终

您必须首先交换ifelif以测试<=22

当然,你必须一些事情outcomeG > 25否则你什么都不循环。