Tkinter循環產生checkbutton問題

前兩天遇到一個搞了兩天也解決不了的問題,最後在stackoverflow上被一個大佬帥氣解救了,十分感謝!!寫下來幫助有這個問題的小夥伴~

參考鏈接:https://stackoverflow.com/questions/60699268/tkinter-checkbutton-questions?noredirect=1#comment107397792_60699268

成功的代碼如下:

    def close_yes(i):
        update_rank(solutions[ii])
        tkinter.messagebox.showinfo('notice', 'Finish, thank you!')
        print('close_yes:', i, v[i].get())
        mywindow.destroy()

    def close_no(i):
        if i < len(solutions) - 1:
            tkinter.messagebox.showinfo('notice', 'Please try next solution')
        if i == len(solutions) - 1:
            var_string = askstring(title="Tester Troubleshooter",
                                   prompt="Please provide new solution:")
            update_error_list(var_string)
            tkinter.messagebox.showinfo('notice', 'Finish, thank you!')
            mywindow.destroy()
        print('close_no:', i, v[i].get())

    v = [None] * len(solutions)  # list to hold the StringVar instances
    for ii in range(len(solutions)):
        v[ii] = tk.StringVar()
        checkbutton1 = tk.Checkbutton(mywindow, text='YES', onvalue='YES', variable=v[ii],
                                      bg="white", fg="green", font=("times", 10), width=3, anchor="w",
                                      command=lambda i=ii: close_yes(
                                          i))  # use lambda to pass the correct index to callback
        checkbutton1.deselect()
        checkbutton1.grid(row=ii + 1, column=5, ipadx=0, ipady=0, rowspan=1, sticky=tk.N + tk.E + tk.S + tk.W)
        checkbutton2 = tk.Checkbutton(mywindow, text='NO', onvalue='NO', variable=v[ii],
                                      bg="white", fg="red", font=("times", 10), width=3, anchor="w",
                                      command=lambda i=ii: close_no(i))
        checkbutton2.deselect()
        checkbutton2.grid(row=ii + 1, column=6, ipadx=0, ipady=0, rowspan=1, sticky=tk.N + tk.E + tk.S + tk.W)

原來錯誤的代碼如下:

for ii in range(len(solutions)):
tk.Label(text=solutions[ii], bg="lightsalmon", fg="black", font=("times", 10), relief=tk.RIDGE, width=50, anchor="w").grid(row=ii+1,column=3, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
v = StringVar()
checkbutton1 = Checkbutton(mywindow, text='YES', onvalue='YES', variable=v, bg="red", fg="black", font=("times", 10), width=3, anchor="w", command=close_yes)
checkbutton1.deselect()
checkbutton1.grid(row=ii+1, column=4, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)
checkbutton2 = Checkbutton(mywindow, text='NO', onvalue='NO', variable=v, bg="red", fg="black", font=("times", 10), width=3, anchor="w", command=close_no)
checkbutton2.deselect()
checkbutton2.grid(row=ii+1, column=5, ipadx=0, ipady=0, rowspan=1, sticky=tk.N+tk.E+tk.S+tk.W)

界面如下:

我的問題在於,通過for循環每個for循環建立一個YES和一個NO按鈕,但是不管我按哪個按鈕,得到的都是最後一個for循環產生的按鈕的值。

後來大佬幫忙加了Lambda函數,就好了!!!

跪謝!

有需要的小夥伴可以參考一下!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章