This can be done using a lambda, like so:
button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))
This is a simple way to bind the argument without an explicit wrapper method or modifying the original action.
This can be done using a lambda, like so:
button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))
This is a simple way to bind the argument without an explicit wrapper method or modifying the original action.
This can also be done by using partial from the standard library functools, like this:
from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)
How to use a Tkinter button (call a function) that has an argument?
How to call same function with different argument given from list in tkinter button command option
Passing variables into Tkinter button click event
Tkinter button command using lambda to call a class method - how???
Videos
Hello everyone,
I have a Tkinter window that is defined in a class, and I have a function that gets a value from the Tkinter window.
I.E.
class newTopLevel(object):
def __init__(self, root):
self.newWindow = Toplevel(root)
entry_1 = tk.Entry(self.newWindow).grid(row=0, column=1)
self.newWindow.btn = tk.Button(self.newWindow,text='Enter',command=self.fun)
self.newWindow.btn.grid(row=0,column=2)
def fun(self):
get_value=entry_1.get()The issue here is entry_1 is not defined in my function. I normally don't have my Tkinter within a class, thus its a global and its properties (such as buttons and entry grids) are globals and they don't have to be defined. However in this case, now it does need to defined. I tried this:
def fun(self,entry_1):
get_value=entry_1.get()However, then I cannot use the button command to call it.
self.newWindow.btn = tk.Button(self.newWindow,text='Enter',command=self.fun(entry_1))
If I don't include the argument entry_1, then I'll get an error that fun has an argument and I haven't given any when using the button. I don't quite know how to use a Tkinter button that has arguments. Any help would be greatly appreciated!
I'm close, but I think I'm missing something fundamental.
I'm programatically building some tkinter buttons and trying to get them to set a variable to some value (in this case, their own array index).
from tkinter import *
btnarray = [] array = []
def BtnClicked(obj, value):
obj = value
def CreateWindow():
for idx in range(10):
array.append(0)
btnarray.append(Button(root, text = f"Button {idx}", command = lambda a = idx: BtnClicked( array[a] , a)))
btnarray[-1].pack()
root = Tk()
CreateWindow()
while True:
root.update() structure is representative of the application I inherited and am trying to alter. Why isn't it writing the values to array? if I break inside 'BtnClicked', obj gets the value written, but that somehow doesn't pass back to array.
Thanks!