所以我的计算类正在使用python制作一张圣诞卡,其中一个位将会有一个带有消息的文本框,但是如何使背景从绿色和红色交替?
如果有人能够帮助那将是惊人的:)
from tkinter import *
root = Tk()
root.title("Xmas Message")
#command for the button
def test_com():
#removing the button
act_btn.grid_remove()
#adding the textbox for the message
msg_box = Text(root, height = 1, width = 30)
msg_box.grid(row=0, column=0)
#adding the message
msg_box.insert(END, "Happy Xmas")
#changing the background to green
msg_box.config(background="green")
#changing the background to red
msg_box.config(background="red")
root.after(250, test_com)
#button for activating the command
act_btn = Button(root, text = "1", command = test_com)
act_btn.grid(row=0, column=0)
root.mainloop()
解决方法:
创建一个change_color回调,用于交替显示文本框的颜色,并使用after在将来调用自己的颜色.
示例实施:
from tkinter import *
def change_color():
current_color = box.cget("background")
next_color = "green" if current_color == "red" else "red"
box.config(background=next_color)
root.after(1000, change_color)
root = Tk()
box = Text(root, background="green")
box.pack()
change_color()
root.mainloop()