Как я могу получить доступ к данным пера планшета через Python?

Мне нужно получить доступ к данным пера планшета Windows (например, к поверхности) через Python. В основном мне нужны значения положения, давления и наклона.

Я знаю, как получить доступ к данным пера Wacom, но перо Windows отличается.

Существует библиотека Python с именем Kivy, которая может обрабатывать мультитач, но распознает мое перо как палец (WM_TOUCH ), а не как перо (WM_PEN).

Это мой код Kivy (который не сообщает о давлении и наклоне):

 from kivy.app import App
 from kivy.uix.widget import Widget

class TouchInput(Widget):

def on_touch_down(self, touch):
    print(touch)
def on_touch_move(self, touch):
    print(touch)
def on_touch_up(self, touch):
    print("RELEASED!",touch)

class SimpleKivy4(App):

def build(self):
    return TouchInput()

Существует замечательная обрабатывающая библиотека с именем Планшет, который работает только с планшетом Wacom с простым API (например, tablet.getPressure())

Мне нужно что-то вроде этого.


person Roi Yozevitch    schedule 02.01.2019    source источник


Ответы (2)


если вы хотите увидеть устройства:

import pyglet
pyglet.input.get_devices()

если вы хотите увидеть элементы управления устройствами:

tablets = pyglet.input.get_devices() #tablets is a list of input devices
tablets[0].get_controls() #get_controls gives a list of possible controls of the device  

А теперь, чтобы получить данные. У меня есть планшет xp-pen g640, и у него нет датчика наклона, но если он есть у вас, код будет легко изменить:

if tablets:
    print('Tablets:')
    for i, tablet in enumerate(tablets):
        print('  (%d) %s' % (i , tablet.name))
i = int(input('type the index of the tablet.'))

device = tablets[i]
controls = device.get_controls()
df = pd.DataFrame()
window = pyglet.window.Window(1020, 576)

# Here you will have to write a line like "control_tilt_x = controls[j]" where j is
# the controls list index of the tilt control.
control_presion = controls[7]
Button = controls[3]
control_x =controls[5]
control_y =controls[6]
control_punta = controls[4]
control_alcance = controls [0]
name = tablets[9].name

try:
    canvas = device.open(window)
except pyglet.input.DeviceException:
    print('Failed to open tablet %d on window' % index)

print('Opened %s' % name)

    
@control_presion.event
def on_change(presion):
    global df   
    df_temp = pd.DataFrame({'x':[control_x.value/(2**15)],
                           'y':[control_y.value/(2**16)],
                           'p':[control_presion.value/8],
                           't':[time.time()]})
    df = pd.concat([df,df_temp])
          
pyglet.app.run()
person Francisco Iaconis    schedule 28.02.2021

Это решение работает для меня, адаптировано для Python 3 из здесь .

Что работает: ручка, ластик, кнопки ручки, оба датчика давления.

Сначала установите библиотеку pyglet: pip install pyglet. Затем используйте код:

import pyglet

window = pyglet.window.Window()
tablets = pyglet.input.get_tablets()
canvases = []

if tablets:
    print('Tablets:')
    for i, tablet in enumerate(tablets):
        print('  (%d) %s' % (i + 1, tablet.name))
    print('Press number key to open corresponding tablet device.')
else:
    print('No tablets found.')

@window.event
def on_text(text):
    try:
        index = int(text) - 1
    except ValueError:
        return

    if not (0 <= index < len(tablets)):
        return

    name = tablets[i].name

    try:
        canvas = tablets[i].open(window)
    except pyglet.input.DeviceException:
        print('Failed to open tablet %d on window' % index)

    print('Opened %s' % name)

    @canvas.event
    def on_enter(cursor):
        print('%s: on_enter(%r)' % (name, cursor))

    @canvas.event
    def on_leave(cursor):
        print('%s: on_leave(%r)' % (name, cursor))

    @canvas.event
    def on_motion(cursor, x, y, pressure, a, b):  # if you know what "a" and "b" are tell me (tilt?)
        print('%s: on_motion(%r, x=%r, y=%r, pressure=%r, %s, %s)' % (name, cursor, x, y, pressure, a, b))

@window.event
def on_mouse_press(x, y, button, modifiers):
    print('on_mouse_press(%r, %r, %r, %r' % (x, y, button, modifiers))

@window.event
def on_mouse_release(x, y, button, modifiers):
    print('on_mouse_release(%r, %r, %r, %r' % (x, y, button, modifiers))

pyglet.app.run()
person Rabash    schedule 02.07.2019
comment
Спасибо. Я попробовал ваш код, но когда я перемещаю перо поверхности, я получаю только события мыши (нажатие, отпускание) и никаких событий движения, плюс я не получаю планшет не найден Таблетки не найдены. on_mouse_press(448, 150, 1, 16 on_mouse_release(273, 324, 1, 16) on_mouse_press(252, 318, 1, 16 on_mouse_release(237, 151, 1, 16) - person Roi Yozevitch; 03.07.2019
comment
@RoiYozevitch, отсутствие таблеток означает плохие новости. Возможно, вам нужны драйвера, или ваше устройство слишком новое. Я использую Wacom Bamboo. - person Rabash; 03.07.2019