Tkinter custom window

前端 未结 2 608
醉梦人生
醉梦人生 2020-12-12 02:15

I want to make a window in Tk that has a custom titlebar and frame. I have seen many questions on this website dealing with this, but what I\'m looking for is to actually re

2条回答
  •  北海茫月
    2020-12-12 02:38

    Here is a rough example where the frame, titlebar and close button are made with canvas rectangles:

    import Tkinter as tk
    
    class Application(tk.Tk):
    
        def __init__(self):
            tk.Tk.__init__(self)
            # Get rid of the os' titlebar and frame
            self.overrideredirect(True)
    
            self.mCan = tk.Canvas(self, height=768, width=768)
            self.mCan.pack()
    
            # Frame and close button
            self.lFrame = self.mCan.create_rectangle(0,0,9,769,
                                        outline='lightgrey', fill='lightgrey')
            self.rFrame = self.mCan.create_rectangle(760,0,769,769,
                                        outline='lightgrey', fill='lightgrey')
            self.bFrame = self.mCan.create_rectangle(0,760,769,769,
                                        outline='lightgrey', fill='lightgrey')
            self.titleBar = self.mCan.create_rectangle(0,0,769,20,
                                        outline='lightgrey', fill='lightgrey')
            self.closeButton = self.mCan.create_rectangle(750,4,760, 18,
                                                activefill='red', fill='darkgrey')
    
            # Binds
            self.bind('<1>', self.left_mouse)
            self.bind('', self.close_win)
    
            # Center the window
            self.update_idletasks()
            xp = (self.winfo_screenwidth() / 2) - (self.winfo_width() / 2)
            yp = (self.winfo_screenheight() / 2) - (self.winfo_height() / 2)
            self.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(),
                                                    self.winfo_height(),
                                                                xp, yp))
    
        def left_mouse(self, event=None):
            obj = self.mCan.find_closest(event.x,event.y)
            if obj[0] == self.closeButton:
                self.destroy()
    
        def close_win(self, event=None):
            self.destroy()
    
    app = Application()
    app.mainloop()
    

    If I were going to make a custom GUI frame I would consider creating it with images,
    made with a program like Photoshop, instead of rendering canvas objects.
    Images can be placed on a canvas like this:

    self.ti = tk.PhotoImage(file='test.gif')
    self.aImage = mCanvas.create_image(0,0, image=self.ti,anchor='nw')
    

    More info →here←

提交回复
热议问题