Having trouble with Tkinter transparency

心不动则不痛 提交于 2019-11-29 15:47:25

问题


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)

This is python 2.6 on Windows 7.


回答1:


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.

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.

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


来源:https://stackoverflow.com/questions/3399882/having-trouble-with-tkinter-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!