tkinter: Copy to clipboard via button

Question:

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.

Asked By: Noxramus

||

Answers:

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()
Answered By: Novel

I suggest displacing the part of syntax command=lambda: gtc(age) by command=lambda x = age : gtc(x) as well as command=lambda: gtc(gage) by command=lambda y = gage : gtc(y), which would make the entire syntax more smoother and interpreter run without errors. Moreover, if in the future, any situations to modify the syntax, especially in for loop syntax combination that will be merged fluidly.

Answered By: niel liang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.