首页 > 解决方案 > 按下按钮时如何开始闪烁我的文本标签?

问题描述

我试图在 tkinter 中创建一个文本标签,当按下“1”按钮时它应该开始闪烁。为此,我在 tkinter 文档和谷歌上的其他教程的帮助下进行了尝试,但由于我是 python 新手,最终未能成功创建逻辑,我发现处理事件对象并不难。这是我的代码。

import tkinter as Tk

flash_delay = 500  # msec between colour change
flash_colours = ('white', 'red') # Two colours to swap between

def flashColour(object, colour_index):
    object.config(background = flash_colours[colour_index])
    root.after(flash_delay, flashColour, object, 1 - colour_index)

root = Tk.Tk()
root.geometry("100x100")
root.label = Tk.Text(root, text="i can flash",
                   background = flash_colours[0])
root.label.pack()
#root.txt.insert(Tk.END,"hello")


root.button1=Tk.Button(root,text="1")
root.button1.pack()

root.button.place(x=10,y=40,command = lambda: flashColour(root.label, 0))
root.mainloop()

标签: pythontkinter

解决方案


place不接受command作为论据。您应该将它传递给Button带有lambda.

root.button=Tk.Button(root,text="1",command = lambda: flashColour(root.label, 0))
root.button.pack()
#root.button.place(x=10,y=40)  # you should use either `pack` or `place` but not both

推荐阅读