如何在tkinter中制作闪烁的文本框?

问题描述 投票:0回答:2

所以我的计算课正在用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()
python python-3.x textbox tkinter
2个回答
8
投票

创建一个

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

0
投票

我改编了Kevin的answer并将其变成了一个单独的函数。

from tkinter import *

def flash_entry(this_entry, colorlist, ms = 1000):
    """      
    Flash the offending entry box through the colorlist, one color every 'ms' milliseconds.
    Example:
        flash_entry(entry_that_was_invalid,["red","white"])
    """
    thiscolor = colorlist.pop(0)
    this_entry.config(background = thiscolor)
    top = this_entry._nametowidget(this_entry.winfo_parent())
    if len(colorlist) > 0:
        top.after(ms, lambda te=this_entry, c=colorlist, ms=ms: flash_entry(te,c,ms))

我还没有尝试将此函数连接到 validatecommand/invalidcommand,但这将是一个有趣的组合。我自己有自己单独的验证逻辑,如果它发现我的输入文本无效,它会运行以下命令:

my_lib_name.flash_entry(self.ent_prof2name,["red","white","red","white","red","white","red","white"],333)
© www.soinside.com 2019 - 2024. All rights reserved.