Home > OS >  I am having trouble with a button in my first gui application
I am having trouble with a button in my first gui application

Time:01-07

def play():
    wind2 = tk.Toplevel()
    v = tk.IntVar()
    ques = ["Identify the least stable ion amongst the following.",
            "The set representing the correct order of first ionisation potential is",
            "The correct order of radii is"]
    o1 = ["", "Li⁺", "Be⁻", "B⁻", "C⁻"]
    o2 = ["", "K > Na > Li", "Be > Mg >Ca", "B >C > N", "Ge > Si >C"]
    o3 = ["", "N < Be < B", "F⁻ < O²⁻ < N³⁻", "Na < Li < K", "Fe³⁺ < Fe⁴⁺ < Fe²⁺"]
    choice=[o1, o2, o3]
    qsn = tk.Label(wind2, text = ques[0])
    qsn.pack()

    

    def correct():
        selected=v.get()
        print(selected)
        
    r1 = tk.Radiobutton(wind2, text = o1[1], variable = v, value = 1, command=correct)
    r2 = tk.Radiobutton(wind2, text = o1[2], variable = v, value = 2, command=correct)
    r3 = tk.Radiobutton(wind2, text = o1[3], variable = v, value = 3, command=correct)
    r4 = tk.Radiobutton(wind2, text = o1[4], variable = v, value = 4, command=correct)
    r1.pack()
    r2.pack()
    r3.pack()
    r4.pack()

    def nxt():
        n = random.randint(1,2)
        qsn['text'] = ques[n]
        r1['text'] = choice[n][1]
        r2['text'] = choice[n][2]
        r3['text'] = choice[n][3]
        r4['text'] = choice[n][4]
    nbut = tk.Button(wind2, text = "next", command = lambda: nxt)
    nbut.pack()

I am trying to change the question using the button nbut, and it won't work. I tried using randint outside the function and passing it but then the button works only once

CodePudding user response:

Change

nbut = tk.Button(wind2, text = "next", command = lambda: nxt)

To this.

nbut = tk.Button(wind2, text = "next", command = nxt) # Recommended
## OR

# nbut = tk.Button(wind2, text = "next", command = lambda: nxt())

The explanation is simple.

You are not calling the nxt function when nbut click Instead you are calling the lambda function. But, because you put the function name inside the lambda function without parentheses the nxt function never executes.

  • Related