gpt4 book ai didi

python - 通过鼠标点击从板上选择方 block 的有效方法(Python 3.X.tkinter)

转载 作者:行者123 更新时间:2023-11-30 22:00:05 25 4
gpt4 key购买 nike

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

在工作时我想出了这个简单的实现:

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 板来说,这看起来不错(至少对我来说),但是当设计更大的板时,它会变得相当大。谁能建议我一个更好的主意来做到这一点,或者至少指出一个好的方向?谢谢!

最佳答案

如果您不需要 Canvas ,我认为更好的方法是构建标签。

您将需要 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

关于python - 通过鼠标点击从板上选择方 block 的有效方法(Python 3.X.tkinter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54422672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com