【问题标题】:How to add custom Frame borders in Python Tkinter如何在 Python Tkinter 中添加自定义框架边框
【发布时间】:2022-12-08 20:43:57
【问题描述】:

我正在使用 Tkinter 构建一个 GUI 应用程序。我正在创建 9 个按钮,每行 3 个。我想让它只在它们之间绘制边框,上下没有边框。这可以用 Tkinter 完成吗?

    buttons_frame = [tk.Frame(
        self.root,
        highlightbackground="black",
        highlightcolor="black",
        highlightthickness=1,
        bd=0
    ) for i in range(9)]

    self.field_buttons = [tk.Button(
        buttons_frame[i],
        width=5,
        height=2,
        relief='flat',
        padx=1,
        font=('Arial', 20, 'bold'),
        command=lambda x=i: self.push(x)
    ) for i in range(9)]

    row, col = 1, 0
    for i in range(9):
        buttons_frame[i].grid(row=row, column=col, sticky='news')
        self.field_buttons[i].grid(row=row, column=col, sticky='news')
        col += 1
        if col == 3:
            row += 1
            col = 0

【问题讨论】:

    标签: python tkinter border frame


    【解决方案1】:

    是的,可以使用 Tkinter 创建一个 GUI 应用程序,该应用程序具有按行排列的按钮,在按钮之间绘制边框,但不能在按钮上方或下方绘制。这可以通过使用 Tkinter 中的框架小部件来完成,它允许您为其他小部件创建容器并控制它们的布局和外观。

    下面是一个示例,说明如何使用 Tkinter 中的框架小部件创建具有三行按钮的 GUI,在按钮之间绘制边框,但不在按钮上方或下方绘制边框:

        from tkinter import *
    
        root = Tk()
    
        # Create a frame widget with 3 rows and 3 columns
        frame = Frame(root, rows=3, columns=3)
    
        # Loop through the rows and columns of the frame
        for row in range(3):
            for column in range(3):
        # Create a button widget and add it to the frame
        button = Button(frame, text="Button")
        button.grid(row=row, column=column, sticky="nsew")
    
        # Configure the frame to expand with the window
        frame.pack(expand=True, fill="both")
    
        root.mainloop()
    

    在此示例中,我们创建了一个具有 3 行和 3 列的框架小部件,然后遍历行和列以将按钮添加到框架中。我们使用 grid 方法将按钮定位在框架中,并指定 sticky 选项以确保按钮扩展以填充边框之间的空间。最后,我们使用 pack 方法将框架配置为随窗口扩展,以便按钮始终以完整尺寸显示。

    此代码将创建一个具有三行按钮的 GUI,在按钮之间绘制边框,但不会在它们上方或下方绘制。您可以修改此代码以自定义按钮的布局和外观,并根据需要向您的应用程序添加其他小部件和功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-06
      • 2011-05-06
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多