Home > Net >  Python, Kivy: How to copy to clipboard on the click of a button?
Python, Kivy: How to copy to clipboard on the click of a button?

Time:03-12

I would like to copy a text to the clipboard with the click of a button. Example code:

.py

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager

sm = ScreenManager()

class main(Screen):
    def generate(self):
        text = 'Testing123456'
        #copy to clipboard

class MyApp(App):
    def build(self):
        sm.add_widget(main(name='main'))

        return sm

if __name__ == '__main__':
    MyApp().run()

.kv

<main>
    FloatLayout:
        Button:
            text: 'Generate'
            font_size: (self.height - len(self.text) * 2) / 2
            size_hint: 0.5, 0.2
            pos_hint: {'x': 0.25, 'y': 0.1}
            on_release: root.generate()

There is more of my code, but I decided to remove it because that would be off-topic. Should you need the rest of my code, feel free to tell me so.

Help is appreciated!!

CodePudding user response:

You didn't explain what is your problem but you have all in documentation: Clipboard

from kivy.core.clipboard import Clipboard
 
class main(Screen):
    def generate(self):
        text = 'Testing123456'
        Clipboard.copy(text)

And this works for me on Linux.

CodePudding user response:

If you are working on Windows OS, you can create a nested function in conjunction with OS module to calling a cmd function:

import os
def addToClipBoard(text):
    command = 'echo '   text.strip()   '| clip'
    os.system(command)

a = input("Ingrese el dato:")
addToClipBoard(a)

You can add this function to your event detector of your button with Kivy

  • Related