代码之家  ›  专栏  ›  技术社区  ›  Aivaras Kazakevičius

一种通过鼠标点击板来选择正方形的有效方法(Python 3.X.tkinter)

  •  1
  • Aivaras Kazakevičius  · 技术社区  · 7 年前

    我正在寻找一种更有效的方法,通过鼠标点击从矩形板上选择正方形。

    在工作中,我提出了以下简单实现:

    import tkinter as tk
    
    
    def square_selector(event):
        if 1 <= event.x <= 199 and 1 <= event.y <= 199:
            print('This is square 1')
        elif 1 <= event.x <= 199 and 201 <= event.y <= 399:
            print('This is square 2')
        elif 1 <= event.x <= 199 and 401 <= event.y <= 599:
            print('This is square 3')
        elif 201 <= event.x <= 399 and 1 <= event.y <= 199:
            print('This is square 4')
        elif 201 <= event.x <= 399 and 201 <= event.y <= 399:
            print('This is square 5')
        elif 201 <= event.x <= 399 and 401 <= event.y <= 599:
            print('This is square 6')
        elif 401 <= event.x <= 599 and 1 <= event.y <= 199:
            print('This is square 7')
        elif 401 <= event.x <= 599 and 201 <= event.y <= 399:
            print('This is square 8')
        elif 401 <= event.x <= 599 and 401 <= event.y <= 599:
            print('This is square 9')
        else:
            pass
    
    
    root = tk.Tk()
    
    canvas = tk.Canvas(height=600, width=600)
    canvas.pack()
    
    canvas.create_line(0, 200, 600, 200)
    canvas.create_line(0, 400, 600, 400)
    canvas.create_line(200, 0, 200, 600)
    canvas.create_line(400, 0, 400, 600)
    
    canvas.bind('<Button-1>', square_selector)
    
    root.mainloop()
    

    这看起来不错(至少对我来说)与3x3板,但它会变得相当大,当设计一个更大的板。有谁能给我一个更好的建议,或者至少指出一个好的方向?谢谢

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mike - SMT    7 年前

    您将需要1x1像素图像才能执行此操作,因为默认情况下标签的大小基于字体大小而不是像素大小。通过向标签添加1x1像素图像,我们可以通过像素定义高度和宽度。

    我还更喜欢使用列表来存储标签和您可能希望与标签一起存储的其他变量。

    这也是动态伸缩的。

    你不需要将数字应用到框中,我只是为了视觉表现而这样做的。

    import tkinter as tk
    
    
    def square_selector(square):
        print(square)
    
    root = tk.Tk()
    label_list = []
    counter = 1
    img = tk.PhotoImage(file='1x1.png')
    
    grid_size = 4
    box_size = 100
    
    for x in range(grid_size):
        for y in range(grid_size):
            label_list.append(tk.Label(root, text=counter, image=img, width=box_size, height=box_size,
                                       compound='center', borderwidth=1, relief="solid"))
            label_list[-1].grid(row=x, column=y)
            label_list[-1].bind('<Button-1>', lambda e, c=counter: square_selector(c))
            counter += 1
    
    root.mainloop()
    

    结果:

    enter image description here

        2
  •  1
  •   Jacques Gaudin    7 年前

    您可以这样做:

    def square_selector(event):
        sq_num = (event.x // 200) * 3 + (event.y // 200) + 1
        print("This is square {0}".format(sq_num))
    

    //