2

ラベルの色をランダムにしようとしていますが、一番下のコードを試しましたが、うまくいきません。色は、レッド、グリーン、ブルー、イエロー、オレンジ、ホワイト、シアン、パープルです。単一の色として表示するにはどうすればよいですか?

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'white', 'cyan', 'purple']
    class Example(Frame):

        def __init__(self, parent):
            Frame.__init__(self, parent, background="white")

            self.parent = parent

            self.initUI()

        def initUI(self):

            self.parent.title("Credits")

            self.pack(fill=BOTH, expand=1)
            label1 = Label(self, text="Code by blaba, fg=colors, bg=colors)
            label1.pack()
            label2 = Label(self, text="Idea by noctize", fg=colors, bg=colors)
            label2.pack()
            label3 = Label(self, text="Packed using py2exe", fg=colors, bg=colors)
            label3.pack()
            colorbutton = Button


            quitButton = Button(self, text="Quit",
                command=self.quit)
            quitButton.place(x=50, y=70)


    def main():

        root = Tk()
        root.geometry("250x150+300+300")
        app = Example(root)
        root.mainloop()


    if __name__ == '__main__':
        main()

どうしてうまくいかないの?

4

2 に答える 2

2

colors色の名前ではなく色のリストであるため、コードは機能しません。

random.choice次のように、ランダムな色を選択するために使用できます。

import random

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'white', 'cyan', 'purple']
#your class declaration, __init__ declaration and more
def initUI(self):
        randomized = []
        for i in range(3):
            #this will pick three of the colors to be the color
            randomized.append(random.choice(colors))

        self.parent.title("Credits")
        self.pack(fill=BOTH, expand=1)
        label1 = Label(self, text="Code by blaba", fg=randomized[0], bg=randomized[0])
        label1.pack()
        label2 = Label(self, text="Idea by noctize", fg=randomized[1], bg=randomized[1])
        label2.pack()
        label3 = Label(self, text="Packed using py2exe", fg=randomized[2], bg=randomized[2]
        label3.pack()
        colorbutton = Button

また、label1宣言のタイプミスを修正しました。

お役に立てれば!

于 2013-11-06T12:42:07.680 に答える