我可以更改Tkinter的标题栏吗?

2024-06-28 11:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Tkinter作为程序的GUI,但正如我所见,许多程序不像Tkinter那样具有标准外观。我说的标准外观是指标准的标题栏、边框等

例如,Tkinter的标题栏:

http://pokit.org/get/img/1a343ad92cd8c8f19ce3ca9c27afecba.jpg

对比GitHub的标题栏:

http://pokit.org/get/img/cf5cef0eeae5dcdc02f450733fd87508.jpg

看看他们如何有自己的自定义退出,调整大小和最小化按钮?用Tkinter能达到那种效果吗?

提前谢谢!:)


Tags: 程序github标准tkintergui按钮边框外观
3条回答

在python3.5.2中,我必须做一些修改才能使其生效:

#custom title bar for tkinter

from tkinter import Tk, Frame, Button, Canvas

root = Tk()

def move_window(event):
    root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))

root.overrideredirect(True) # turns off title bar, geometry
root.geometry('400x100+200+200') # set new geometry

# make a frame for the title bar
title_bar = Frame(root, bg='white', relief='raised', bd=2)

# put a close button on the title bar
close_button = Button(title_bar, text='Close this Window', command=root.destroy)

# a canvas for the main area of the window
window = Canvas(root, bg='black')

# pack the widgets
title_bar.pack(expand=1, fill="x")
close_button.pack(side="right")
window.pack(expand=1, fill="both")

# bind title bar motion to the move window function
title_bar.bind('<B1-Motion>', move_window)

root.mainloop()

大多数人都知道在使用上面使用的“move_window”方法时会出现错误;我找到了一个修复程序,它可以获取鼠标的确切位置并随鼠标移动,而不是从角落移动:

    def get_pos(event):
        xwin = app.winfo_x()
        ywin = app.winfo_y()
        startx = event.x_root
        starty = event.y_root

        ywin = ywin - starty
        xwin = xwin - startx


        def move_window(event):
            app.geometry("400x400" + '+{0}+{1}'.format(event.x_root + xwin, event.y_root + ywin))
        startx = event.x_root
        starty = event.y_root


        app.TopFrame.bind('<B1-Motion>', move_window)
    app.TopFrame.bind('<Button-1>', get_pos)

是的,这是可能的。可以使用根窗口上的^{}方法终止标题栏和默认几何设置。在那之后,您需要从头开始重建所有这些方法,以按您的需要设置它。下面是一个最小功能的小工作示例:

root = Tk()

def move_window(event):
    root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))

root.overrideredirect(True) # turns off title bar, geometry
root.geometry('400x100+200+200') # set new geometry

# make a frame for the title bar
title_bar = Frame(root, bg='white', relief='raised', bd=2)

# put a close button on the title bar
close_button = Button(title_bar, text='X', command=root.destroy)

# a canvas for the main area of the window
window = Canvas(root, bg='black')

# pack the widgets
title_bar.pack(expand=1, fill=X)
close_button.pack(side=RIGHT)
window.pack(expand=1, fill=BOTH)

# bind title bar motion to the move window function
title_bar.bind('<B1-Motion>', move_window)

root.mainloop()

相关问题 更多 >