如何在按下按钮时更改tkinter python中的帧颜色?

时间:2018-01-15 19:36:57

标签: python user-interface tkinter frame

按下按钮时有没有办法让画面背景颜色发生变化?

1 个答案:

答案 0 :(得分:1)

是的,只需将frame['bg']设置为格式为'#000000'named color references的十六进制RGB值,即可通过多种方式实现此目的。以下buttonframe的背景颜色更改为'medium sea green'

import tkinter as tk


def change_bg(widget):
    widget['bg'] = 'medium sea green'


if __name__ == '__main__':
    root = tk.Tk()

    frame = tk.Frame(root, height=100, width=100)
    button = tk.Button(root, text="Paint")
    button['command'] = lambda wgt=frame : change_bg(wgt)

    frame.pack()
    button.pack()

    root.mainloop()

下面是一个示例,其中frame通过RGB格式循环其背景颜色:

import tkinter as tk


def cycle(event, widget):
    if widget['bg'][0] != '#':
        widget['bg'] = "#000000"
    else:
        widget['bg'] = '#' + str(int(widget['bg'][1:]) + 1).zfill(6)


if __name__ == '__main__':
    root = tk.Tk()

    frame = tk.Frame(root, height=200, width=200)
    frame.bind('<Button-1>', lambda event, widget=frame: cycle(event, widget))
    frame.pack()

    root.mainloop()