For循环因未知原因而无法正常工作

时间:2016-11-05 00:15:19

标签: python python-3.x loops tkinter

我有这段代码:

def show_hide(a, b, c, d):
    if not b[0]["text"]:  # check if text's length is 0
        b[0].configure(text="{}".format(d[0]), bd=2, bg="white", command=lambda: activate_deactivate(a[0], c[0]))  # configure button_1
        c[0]["text"] = "Status: {}".format(a[0].get())  # set text for label_1
        b[1].configure(text="{}".format(d[1]), bd=2, bg="white", command=lambda: activate_deactivate(a[1], c[1]))  # configure button_2
        c[1]["text"] = "Status: {}".format(a[1].get())  # set text for label_2
    else:
        b[0].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide the button_1
        c[0]["text"] = ""  # hide the label_1
        b[1].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide the button_2
        c[1]["text"] = ""  # hide the label_2

调用此函数的我的按钮具有以下命令值:

command=lambda: show_hide([status, status_2], [button, button_2], [label, label_2], ["Perform action #1", "Perform action #2"]))

通过使用它,我可以显示/隐藏按钮,但重写相同的事情,在一些地方改变一个数字将是乏味的。要修复它,我尝试使用此代码而不是原始代码:

def show_hide(a, b, c, d):
    for i in range(0, len(a)):  # iterates over indexes of items in a,b,c,d lists (all 4 have same length) and passes them to the if/else statement
        if not b[i]["text"]:  # check if text length is 0
            b[i].configure(text="{}".format(d[i]), bd=2, bg="white", command=lambda: activate_deactivate(a[i], c[i]))  # configure buton
            c[i]["text"] = "Status: {}".format(a[i].get())  # set label's text
        else:
            b[i].configure(text="", bd=0, bg="#F0F0F0", command=None)  # hide button
            c[i]["text"] = ""  # hide label

理论上,这应该可以正常工作,只使用4行代码(不计算/ if / else行)与原始函数做同样的事情,对于EACH状态+按钮+标签创建需要4行。但是,事实上,它使我的2个按钮完全错误。

我真的不明白它有什么问题,所以我无法完全描述问题,但你可以通过使用我制作的测试脚本并用showxh替换show_hide函数定义来亲眼看看。一个使用for循环:

import tkinter as tk
import random


class ActionButton(tk.Button):
    def __init__(self, *args, **kwargs):
        tk.Button.__init__(self, *args, **kwargs)
        self.configure(text="", font="courier 20", bd=0)


class ActionLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        tk.Label.__init__(self, *args, **kwargs)
        self.configure(text="", font="courier 14")


def multi(*args):
    for func in args:
        return func


def show_hide(a, b, c, d):
    if not b[0]["text"]:
        b[0].configure(text="{}".format(d[0]), bd=2, bg="white", command=lambda: activate_deactivate(a[0], c[0]))
        c[0]["text"] = "Status: {}".format(a[0].get())
        b[1].configure(text="{}".format(d[1]), bd=2, bg="white", command=lambda: activate_deactivate(a[1], c[1]))
        c[1]["text"] = "Status: {}".format(a[1].get())
    else:
        b[0].configure(text="", bd=0, bg="#F0F0F0", command=None)
        c[0]["text"] = ""
        b[1].configure(text="", bd=0, bg="#F0F0F0", command=None)
        c[1]["text"] = ""


def activate_deactivate(a, c):
    if a.get() == "Can be done":
        a.set("To be done")
        c.configure(text="Status: {}".format(a.get()), fg="blue")
    else:
        a.set("Can be done")
        c.configure(text="Status: {}".format(a.get()), fg="black")


def step_forward(a, b, c):
    if a.get() == "To be done":
        b.configure(text="", bd=0, bg="#F0F0F0", state="disabled")
        c["text"] = ""
        result = random.choice(["success", "failure"])
        if result == "success":
            a.set("Accomplished")
            c["fg"] = "green"
        else:
            a.set("Failed")
            c["fg"] = "red"
    else:
        b.configure(text="", bd=0, bg="#F0F0F0", command=None)
        c["text"] = ""


root = tk.Tk()

status = tk.StringVar()
status.set("Can be done")

status_2 = tk.StringVar()
status_2.set("Can be done")

main = tk.Button(root, text="Show/Hide", bg="white", font="courier 30",
                 command=lambda: show_hide([status, status_2],
                                           [button, button_2],
                                           [label, label_2],
                                           ["Perform action #1", "Perform action #2"]))
main.pack()

frame = tk.Frame(root, pady=10)
frame.pack()

frame_1 = tk.Frame(frame, padx=10)
frame_1.pack(side="left")

frame_2 = tk.Frame(frame, padx=10)
frame_2.pack(side="left")

button = ActionButton(frame_1)
button.grid(row=0, column=0)

label = ActionLabel(frame_1)
label.grid(row=1, column=0)

button_2 = ActionButton(frame_2)
button_2.grid(row=0, column=1)

label_2 = ActionLabel(frame_2)
label_2.grid(row=1, column=1)

next_day = tk.Button(root, text="Next day", bg="white", font="courier 30",
                     command=lambda: multi(step_forward(status, button, label),
                                           step_forward(status_2, button_2, label_2)))
next_day.pack()

root.mainloop()

我希望有人可能知道如何解决这个问题,甚至可能知道如何更改功能以正确执行所有操作。

0 个答案:

没有答案