-2

This is my code:


from tkinter import Tk, Button
import GUI

root = Tk()
b = GUI.time


button1 = Button(
    root, text="Local time", command=b.local_time  # text on top of button
)  # button click event handler
button1.pack()

button2 = Button(
    root, text="Greenwich time", command=b.greenwich_time  # text on top of button
)  # button click event handler
button2.pack()

root.mainloop()

And gets the b.local_time and b.greenwich_time from my class time:

from time import strftime, localtime, gmtime
class time:
    def __init__(self):
        self.gm_time = strftime("Day: %d %b %Y\nTime: %H:%M:%S %p\n", gmtime())
        self.l_time = strftime("Day: %d %b %Y\nTime: %H:%M:%S %p\n", localtime())

    def greenwich_time(self):
        print("Greenwich time:\n" + self.gm_time)

    def local_time(self):
        print("Local time:\n" + self.l_time)

But, when I click in the buttons, I get the errors:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\carol\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: local_time() missing 1 required positional argument: 'self'

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\carol\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: greenwich_time() missing 1 required positional argument: 'self'

Someone could explain to me why is missing the required argument?? Thanks!!!

carol
  • 7
  • 1
  • 7

1 Answers1

2

b = GUI.time doesn't create an instance of your time class; it just makes b another name for the class. As a result, b.local_time isn't bound method; it's the function. Since the button callback isn't provided any arguments when it gets called, the function is missing an argument for the self parameter.

You wanted

b = GUI.time()
chepner
  • 497,756
  • 71
  • 530
  • 681