【问题标题】:How to make the foreground and background colors of a button in Tkinter random如何在 Tkinter 中随机设置按钮的前景色和背景色
【发布时间】:2013-11-06 12:35:07
【问题描述】:

我试图让标签颜色随机化,我尝试了底部的代码,但它不起作用。颜色呈现为红色绿色蓝色黄色橙色白色青色紫色。如何让它显示为单色?

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()

怎么就不行了?

【问题讨论】:

  • 为什么不使用颜色按钮...它甚至不显示

标签: python tkinter


【解决方案1】:

您的代码不起作用,因为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 声明中的一个错字。

希望这会有所帮助!

【讨论】:

  • 得到类似:"全局名称'colors'未定义
  • 变量定义了吗?
  • 只替换initUI的代码,quitButton部分除外。
  • 我已经尝试过了,但我仍然遇到一些错误错误:s17.postimg.org/dl4zchxbj/Untitled.jpg 代码:pastebin.com/9AVgkshc(阅读 tkinter 部分)
  • 已修复。您必须将颜色列表放在 initui 中。谢谢。
【解决方案2】:
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))

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多