1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Noxramus
  • 13
  • 1
  • 4
  • Does this answer your question? [How to pass arguments to a Button command in Tkinter?](https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter) – jasonharper Jan 20 '22 at 21:56

1 Answers1

2

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()
Novel
  • 13,406
  • 2
  • 25
  • 41