Class method not called using button

Post here if you need help with creating a Graphical User Interface in Python.

Class method not called using button

Postby nnani » Wed Jan 08, 2014 12:53 pm

Hello All,

I have just started using python and tkinter.

I am trying to call a method of a class for a button on command options.

Code: Select all
import tkinter as tk
import math
import sys
import turtle

class total_window(tk.Tk):
    "class including info and functions on gui window and system"

    def __init__(self):
        tk.Tk.__init__(self)               
        toolbar = tk.Frame(self)
        toolbar.pack(side="top", fill="x")
        def print_windows():
            print ("This is first output")
        b1 = tk.Button(self, text="Click Here", command = self.print_windows)
        exit_button = tk.Button(self,text="Exit",bg="blue",command = self.destroy)
        b1.pack(in_=toolbar,side ="left")
        exit_button.pack(in_=toolbar,side="right")
        t1 = tk.Text(self, wrap="word")
        t1.pack(side="top", fill="both", expand=True)
demo = total_window()
demo.mainloop()


Executing the above code
Code: Select all
  File "C:/Python33/demo_gui.py", line 21, in __init__
    b1 = tk.Button(self, text="Click Here", command = self.print_windows)
  File "C:\Python33\lib\tkinter\__init__.py", line 1867, in __getattr__
    return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'print_windows'


Please help me understanding this error and how to call a method for using with a button.
nnani
 
Posts: 6
Joined: Tue Jan 07, 2014 10:23 am

Re: Class method not called using button

Postby Yoriz » Wed Jan 08, 2014 1:03 pm

If you want to call print_windows as a method then the indentation is wrong, it would need moving out of the __init__ method and and you need to add self as below.
Code: Select all
class total_window(tk.Tk):
    "class including info and functions on gui window and system"

    def __init__(self):
        #rest of code here

    def print_windows(self):
        print("This is first output")

If you want to call print_windows as a local function then call print_windows without using self.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 781
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Class method not called using button

Postby nnani » Wed Jan 08, 2014 1:15 pm

That worked....Thanks :)
nnani
 
Posts: 6
Joined: Tue Jan 07, 2014 10:23 am


Return to GUI

Who is online

Users browsing this forum: No registered users and 3 guests