I have this code:
from tkinter import *
import tkinter as tk
class App(tk.Frame):
def __init__(self, master):
def print_test(self):
print('test')
def button_click():
print_test()
super().__init__(master)
master.geometry("250x100")
entry = Entry()
test = DoubleVar()
entry["textvariable"] = test
entry.bind('<Key-Return>', print_test)
entry.pack()
button = Button(root, text="Click here", command=button_click)
button.pack()
root = tk.Tk()
myapp = App(root)
myapp.mainloop()
A click on the button throws:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "[somefilepath]", line 10, in button_click
print_test()
TypeError: App.__init__.<locals>.print_test() missing 1 required positional argument: 'self'
While pressing Enter
while in the Entry widget works, it prints:
test
See:
Now if I drop the (self)
from def print_test(self):
, as TypeError: button_click() missing 1 required positional argument: 'self' shows, the button works, but pressing Enter
in the Entry widget does not trigger the command but throws another exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
TypeError: App.__init__.<locals>.print_test() takes 0 positional arguments but 1 was given
How to write the code so that both the button click event and pressing Enter will trigger the print command?