Есть ли способ нажать на все кнопки, на которых я нажал и перетащил мою мышь в tkinter - PullRequest
0 голосов
/ 12 января 2020

Я создал сетку кнопок, и мне нужно изменить цвет кнопок, просто щелкнув и перетащив его. Это связано с тем, что сетка очень велика, и индивидуальное нажатие на каждую кнопку утомительно.

Ответы [ 3 ]

1 голос
/ 12 января 2020

Вы можете привязать <B1-Motion> для захвата событий во время перетаскивания мыши. Внутри связанной функции вы можете использовать метод winfo_containing, чтобы определить, какой виджет находится под курсором.

Пример:

import tkinter as tk

root = tk.Tk()
for row in range(20):
    for column in range(20):
        f = tk.Frame(root, width=20, height=20, bd=1, relief="raised")
        f.grid(row=row, column=column, sticky="nsew")

root.grid_columnconfigure("all", weight=1)
root.grid_rowconfigure("all", weight=1)

def paint(event):
    widget = event.widget.winfo_containing(event.x_root, event.y_root)
    if widget:
        widget.configure(bg="green")

root.bind("<B1-Motion>", paint)
root.mainloop()
0 голосов
/ 12 января 2020

РЕДАКТИРОВАТЬ: Я сделал это несколько часов go, но я должен был сделать что-то другое, и тем временем Брайан Оукли продемонстрировал ту же идею :) Теперь я знаю, что это была хорошая идея.

Но этот метод выбирает все виджеты - даже если вы этого не хотите - поэтому я добавил собственное свойство selectable и использовал hasattr(), чтобы можно было выбирать только некоторые виджеты.


Я использую <B1-Motion> на root для запуска функции, которая использует положение мыши с winfo_containing для распознавания виджета и изменения его фона.

import tkinter as tk

def select(event):
    widget = root.winfo_containing(event.x_root, event.y_root)
    if widget and hasattr(widget, 'selectable'):
        widget['bg'] = 'red'

root = tk.Tk()

for i in range(9):
    for e in range(9):
        b = tk.Button(root, text="X")
        b.selectable = True
        b.grid(row=e, column=i)

root.bind('<B1-Motion>', select)

l = tk.Label(root, text="Label which can't be selected")
l.grid(row=9, column=0, columnspan=9)
b = tk.Button(root, text="Button which can't be selected")
b.grid(row=10, column=0, columnspan=9)
e = tk.Entry(root)
e.insert('end', "Entry which can't be selected")
e.grid(row=11, column=0, columnspan=9)

root.mainloop()

enter image description here

0 голосов
/ 12 января 2020

Я предполагаю, что вы зациклились на функции range () для создания всех кнопок с сеткой.

В следующем коде OOP вы можете изменить все в один клик, а также навести курсор на каждый цвет и тоже измените цвет:

ПРИМЕЧАНИЕ:

  • Нажатие на белую кнопку изменит все на зеленый
  • При наведении курсора на каждый цвет изменит его на синий
from tkinter import *


root = Tk()


def change_myself(button,color_in_hex):
    button.configure(bg = color_in_hex)


class MyButtons():
    def __init__(self,current_color,new_color,button_amount):
        super(MyButtons,self).__init__()
        self._current_color = current_color
        self._new_color = new_color
        self._button_amount = button_amount
        self._buttons_list = list(range(self._button_amount))


    @property
    def buttons_list(self):
        return self._buttons_list

    def __getitem__(self, item):
        return item

    def __setitem__(self, key, value):
        self._buttons_list = value


    def create_buttons(self):
        for a in range(self._button_amount):
            self.buttons_list[a] = Button(root,bg = self._current_color,text = 'Button Number {0}'.format(a))
            print(self.buttons_list[a])
            self.buttons_list[a].grid(row = a,column = 0)
            self.buttons_list[a].bind('<Enter>',lambda event,current_button_index = a: self._buttons_list[current_button_index].configure(bg = '#0000FF'))

        special_button = Button(root,bg = '#FFFFFF',text = 'Changer!')
        special_button.grid(row = 0,column = 1)
        special_button.bind('<Button-1>',lambda event: self.change_everything())

    def change_everything(self):
        for button in self.buttons_list:
            button.configure(bg = self._new_color)

implementation = MyButtons(current_color = '#FF0000',new_color = '#00FF00',button_amount = 10)
implementation.create_buttons()

root.mainloop()

Вот результаты:

Hovering on each button

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...