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 回答
1
de=("%02x"%random.randint(0,255))
re=("%02x"%random.randint(0,255))
we=("%02x"%random.randint(0,255))
ge="#"
color=ge+de+re+we

在 tkinter 中

fill=color

容易,你也可以

fill="#"+("%06x"%random.randint(0,16777215))
于 2014-05-04T00:34:49.860 回答