Кнопка tkinter с зависимым от времени действием - PullRequest
2 голосов
/ 14 июня 2019

Мне нужна помощь для создания кода в Tkinter, который будет выводить различные значения, так как конкретная кнопка удерживается дольше. Так, например, если кнопка а удерживается в течение одной секунды, она выдает 1, или удерживается в течение 5 секунд, она выдает 5 и так далее.


def set_down():
    acl.bind('<Button-1>',gn)
    brk.bind('<Button-1>',gn)


    # set function to be called when released
def set_up():
    acl.bind('<ButtonRelease-1>',fn)
    brk.bind('<ButtonRelease-1>',fn)


def fn(fn):
    print(0,'up')
def gn(gn):
    print(1,'down')

# the actual buttons: 

img = PhotoImage(file='round.gif')
brk_img = PhotoImage(file = 'red.gif')
acl = Button(GUI_CONTROL, text = 'accelerate', command = lambda:[set_down(), set_up()], image = img, padx = 4, pady = 4,
                bg = 'cyan', fg = 'cyan')
acl.place(relx = 0.7, rely = 0.5)

brk = Button(GUI_CONTROL, text = 'break', image = brk_img, command = lambda:[set_down(), set_up()],  padx=4,pady=4)

brk.place(relx = 0.7, rely=0.7)

Итак, у меня уже есть функция для вывода пользователю, удерживается ли она или нет, но теперь мне просто нужно изменить числовое значение в функции печати для fn () и gn (), если она нажата дольше или нет.

1 Ответ

1 голос
/ 14 июня 2019

Вы можете создать подкласс tk.Button, чтобы создать TimePressedButton, который выполняет действие в зависимости от продолжительности нажатия:

import tkinter as tk
import time


class TimePressedButton(tk.Button):
    """A tkinter Button whose action depends on the
    duration it was pressed
    """

    def __init__(self, root):
        super().__init__(root)
        self.start, self.end = 0, 0
        self.set_down()
        self.set_up()
        self['text'] = 'press me'
        self['command'] = self._no_op

    def _no_op(self):
        """keep the tk.Button default pressed/not pressed behavior
        """
        pass

    def set_down(self):
        self.bind('<Button-1>', self.start_time)

    def set_up(self):
        self.bind('<ButtonRelease-1>', self.end_time)

    def start_time(self, e):
        self.start = time.time()

    def end_time(self, e):
        if self.start is not None:  # prevents a possible first click to take focus to generate an improbable time
            self.end = time.time()
            self.action()
        else:
            self.start = 0

    def action(self):
        """defines an action that varies with the duration
        the button was pressed
        """
        print(f'the button was pressed for {self.end - self.start} seconds')
        self.start, self.end = 0, 0


root = tk.Tk()
btn = TimePressedButton(root)
btn.pack()

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