当我点击一个按钮时,颜色字符串将动态变化&在屏幕上打印

时间:2018-05-13 13:34:35

标签: python python-3.x tkinter

我有两个按钮用于在屏幕上打印它们的颜色。

button1 = tk.Button(frame,height = 1, width = 2,bg="Red")
button1.pack()
button2 = tk.Button(frame,height = 1, width = 2,bg="Blue")
button2.pack()

因此,当我点击Button1时,我的字符串(colorchange)将包含"Red"。 当我打印出来然后它将在屏幕上写为==>> Red

1 个答案:

答案 0 :(得分:0)

基本示例代码:

import tkinter as tk

win = tk.Tk()


def change_color_label(color):
    color_change.set(color)

button1 = tk.Button(win, height=1, width=2, bg="Red",
                    command=lambda c='Red': change_color_label(c))
button1.pack()
button2 = tk.Button(win, height=1, width=2, bg="Blue",
                    command=lambda c='Blue': change_color_label(c))
button2.pack()
color_change = tk.StringVar()
mylabel = tk.Label(win, textvariable=color_change)
mylabel.pack()

win.mainloop()

或(out out change_color_label):

import tkinter as tk

win = tk.Tk()

button1 = tk.Button(win, height=1, width=2, bg="Red",
                    command=lambda: color_change.set('Red'))
button1.pack()
button2 = tk.Button(win, height=1, width=2, bg="Blue",
                    command=lambda: color_change.set('Blue'))
button2.pack()
color_change = tk.StringVar()
mylabel = tk.Label(win, textvariable=color_change)
mylabel.pack()

win.mainloop()