【问题标题】:Borders on some sides某些边的边框
【发布时间】:2018-02-01 12:55:59
【问题描述】:

我正在为 tic-tac-toe 变体编写客户端代码。游戏逻辑变化与本题无关

我正在尝试显示如下所示的“哈希标签”井字游戏网格。

我最初考虑在按钮或包含按钮的框架上使用边框,但其他问题在为特定边添加边框时发现困难(以及一些复杂的解决方法)。

我宁愿不使用 Canvas 对象来绘制游戏,因为这感觉 - 就像其他人提到的那样 - 是一种以牺牲可读性为代价的廉价解决方法。

如何在框架/网格列/标签/按钮之间添加这些线?

【问题讨论】:

  • 第一个代码?不明白在哪里?

标签: python tkinter tic-tac-toe


【解决方案1】:

您可以通过将白框放在黑框内并使用gridpadxpady 参数来做到这一点:

import tkinter as tk 

root = tk.Tk()

frame = tk.Frame(root, bg='black')
frames = []
for i in range(3):
    frames.append([])
    for j in range(3):
        frames[i].append(tk.Frame(frame, bg='white', width=50, height=50))
        frames[i][j].grid(row=i, column=j, 
                          padx=((j != 0) * 2,  (j != 2) * 2),
                          pady=((i != 0) * 2,  (i != 2) * 2))

frame.pack()
root.mainloop()

padxpady 可以采用单个数字来获得对称结果或值的元组:padx=(<left>, <right>)pady=(<top>, <bottom>)

【讨论】:

    【解决方案2】:

    这样的事情怎么样:

    # I use python 2
    import Tkinter as tk 
    # For Python 3 use import tkinter as tk 
    
    def create_grid(event=None):
        w = c.winfo_width() # Get current width of canvas
        h = c.winfo_height() # Get current height of canvas
        c.delete('grid_line') # Will only remove the grid_line
    
        # Creates all vertical lines at intevals of 100 except for first and last
        for i in range(100, w - 100, 100):
            c.create_line([(i, 0), (i, h)], tag='grid_line')
    
        # Creates all horizontal lines at intevals of 100 except for first and last
        for i in range(100, h - 100, 100):
            c.create_line([(0, i), (w, i)], tag='grid_line')
    
    root = tk.Tk()
    
    c = tk.Canvas(root, height=300, width=300, bg='white')
    c.pack(fill=tk.NONE, expand=True)
    
    c.bind('<Configure>', create_grid)
    
    root.mainloop()
    

    我接受了this 的回答并稍微调整了一下,这样边缘就不会显示出来了

    【讨论】:

    • 在问题中,我说我宁愿不使用Canvas 对象来绘制游戏
    • @speedstyle 当有人回答您提出的问题时,他们不一定只回答您的问题,而是未来研究人员可能提出的问题。我认为这个答案可能对未来搜索如何具有网格布局的访问者有用。
    • 真;道歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多