简体   繁体   中英

tkinter: Copy to clipboard via button

The idea of the code is to create N amount of buttons that copy text to the clipboard when pressed, overwriting and saving the text from the last pressed button.

from tkinter import *
import tkinter
r = Tk()
age = '''
O.o
    giga
'''
gage = 'vrum'
r.title("getherefast")

def gtc(dtxt):
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append(dtxt)
    r.update()

tkinter.Button(text='age', command=gtc(age)).grid(column=1, row=0)
tkinter.Button(text='gage', command=gtc(gage)).grid(column=2, row=0)

r.mainloop()

With this code I expected to get 2 buttons 'age' and 'gage' and when I press them to get respectively the value saved in the var.

The problem is that the tkinter UI does not load and the Idle window is just standing open.

The result is that I get 'vrum' copied to the clipboard (If age button is the only 1 present I get the correct value but still no GUI from tkinter).

As additional information I'm writing and testing the code in IDLE, Python 3.10.

The problem is that the tkinter UI does not load

Yes it does, but you told it to withdraw() , so you don't see it.

To do this you need a partial or lambda function, you can't use a normal function call in a command argument. Try this:

import tkinter
r = tkinter.Tk()
age = '''
O.o
    giga
'''
gage = 'vrum'
r.title("getherefast")

def gtc(dtxt):
    r.clipboard_clear()
    r.clipboard_append(dtxt)

tkinter.Button(text='age', command=lambda: gtc(age)).grid(column=1, row=0)
tkinter.Button(text='gage', command=lambda: gtc(gage)).grid(column=2, row=0)

r.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM