我想让不那么受欢迎的菜单项从白色逐渐淡入黑色。在菜单仍然打开时,有什么方法可以更新颜色吗?我尝试过postcommand和线程:
def update():
def color(c):
animal_menu.config(fg=c)
root.update()
print c
def adapt():
color('white')
root.after(100, color('#6E6E6E'))
root.after(100, color('black'))
## adapt() ##attempt no.1
## thread.start_new_thread(adapt, ()) ##attempt no.2
root = Tk()
menubutton = Menubutton(root, text="Animals")
animal_menu = Menu(menubutton, tearoff=0, postcommand=update)
animal_menu.add_command(label="Lion", command=print_time)
animal_menu.add_command(label="Tiger", command=print_time)
animal_menu.add_command(label="Bear", command=print_time)
menubutton.menu = animal_menu
menubutton["menu"] = menubutton.menu
menubutton.pack()
root.config()
root.mainloop()到目前为止,第一次尝试在菜单出现之前完全运行(在发布菜单之前调用postcommand是有意义的),而第二次尝试只有在菜单未打开(我不明白)时才运行,打印语句就是证明。
谁能给我一个指针,说明如何使颜色适当地动态变化,使项目在菜单打开时褪色?
发布于 2014-04-10 10:56:07
回调中的after方法有几个问题:
def update():
def color(c):
animal_menu.config(fg=c)
root.update()
print c
def adapt():
color('white')
root.after(100, color('#6E6E6E'))
root.after(100, color('black'))
adapt() ##attempt no.1首先,如果要将参数传递给在“后”中调用的函数,则必须使用lambda表达式或将其拆分为逗号:
root.after(100, color, 'black')否则,括号将使该函数首先进行计算。
第二,after不适用于你可能习惯的典型的控制流--它不是一个,然后是下一个--你在调用后设置两个,在100‘s之后评估,所以这就是将要发生的事情。
下面是fadein回调的一个工作示例:
from Tkinter import *
def fadein(color):
if color < 111111:
animal_menu.config(fg='#000000')
else:
print color
animal_menu.config(fg='#' + str(color))
root.after(100, fadein, color - 111111)
root = Tk()
menubutton = Menubutton(root, text="Animals")
animal_menu = Menu(menubutton, tearoff=0, postcommand=lambda: fadein(999999))
animal_menu.add_command(label="Lion")
animal_menu.add_command(label="Tiger")
animal_menu.add_command(label="Bear")
menubutton.menu = animal_menu
menubutton["menu"] = menubutton.menu
menubutton.pack()
root.config()
root.mainloop()注意postcommand中的lambda表达式,它需要将参数传递给fadein()。
更多信息:http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method
https://stackoverflow.com/questions/22978470
复制相似问题