Tkinter透明性遇到问题 [英] Having trouble with Tkinter transparency

查看:129
本文介绍了Tkinter透明性遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TKinter中,使顶层窗口小部件淡入时遇到了问题.出于某种原因,该小部件根本不会消失,然后它将显示在任务栏中,但是只有在单击两次运行该命令的按钮之后(才应该在任务栏中),该小部件才出现.

I'm having problems making a top level widget fade in, in TKinter. For some reason the widget doesn't fade in at all, then it will show up in the taskbar, but only after clicking the button that runs this command twice (it's not supposed to be in the taskbar).

负责这些问题的代码.

The code responsible for these problems.

    Alpha = 0.0
    w1.attributes("-alpha", Alpha)
    w1.wm_geometry("+" + str(X) + "+" + str(M))
    while 1.0 > Alpha :
        Alpha = Alpha + 0.01
        w1.attributes("-alpha", Alpha)
        sleep(0.005)

这是Windows 7上的python 2.6.

This is python 2.6 on Windows 7.

推荐答案

问题是您的代码永远不允许窗口重新绘制自身.睡眠会导致程序停止,因此不会进入事件循环,而正是事件循环导致了窗口的绘制.

The problem is that your code never allows the window to redraw itself. Sleep causes the program to stop so the event loop isn't entered, and it's the event loop that causes the window to be drawn.

与其休眠,不如利用事件循环并每N毫秒更新一次属性,直到获得所需的Alpha透明度为止.

Instead of sleeping, take advantage of the event loop and update the attributes every N milliseconds until you get the desired alpha transparency you want.

这是在Mac上运行的示例.我认为它也可以在Windows上使用.

Here's an example that works on the mac. I assume it works on windows too.

import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.count = 0
        b=tk.Button(text="create window", command=self.create_window)
        b.pack()
        self.root.mainloop()

    def create_window(self):
        self.count += 1
        t=FadeToplevel(self.root)
        t.wm_title("Window %s" % self.count)
        t.fade_in()


class FadeToplevel(tk.Toplevel):
    '''A toplevel widget with the ability to fade in'''
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.attributes("-alpha", 0.0)

    def fade_in(self):
        alpha = self.attributes("-alpha")
        alpha = min(alpha + .01, 1.0)
        self.attributes("-alpha", alpha)
        if alpha < 1.0:
            self.after(10, self.fade_in)

if __name__ == "__main__":
    app=App()

这篇关于Tkinter透明性遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆