Hick
Hick

Reputation: 36374

Error in gui programming in python using tkinter

#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

import Tkinter

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent=parent
    def initialize(self):
        self.grid()

        self.entry=Tkinter.Entry(self)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>",self.OnPressEnter)

        button=Tkinter.Button(self,test="Post it!",command=self.OnButtonClick)
        button.grid(column=1,row=0)

        label=Tkinter.Label(self,anchor="w",fg="white",bg="blue")
        label=grid(column=0,row=1,columnspan=2,sticky='EW')

        self.grid_columnconfigure(0,weight=1)

    def OnButtonClick(self):
        print "you clicked the button!"

    def OnPressEnter(self,event):
        print "you pressed enter!"

if __name__=="__main__":
    app=simpleapp_tk(None)
    app.title('poster')
    app.mainloop()

I wrote this program so as to make a box to input text and a button, but it shows nothing apart from a window. Where is the error?

Upvotes: 2

Views: 483

Answers (1)

Ben James
Ben James

Reputation: 125119

The main issue was that you forgot to call app.initialize(), but you also had a couple of typos. I've pointed out where in the comments in this fixed version.

import Tkinter

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent=parent
    def initialize(self):
        self.grid()

        self.entry=Tkinter.Entry(self)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>",self.OnPressEnter)

        button=Tkinter.Button(self,text="Post it!",command=self.OnButtonClick)
        # the text keyword argument was mis-typed as 'test'

        button.grid(column=1,row=0)

        label=Tkinter.Label(self,anchor="w",fg="white",bg="blue")
        label.grid(column=0,row=1,columnspan=2,sticky='EW')
        # the . in label.grid was mis-typed as '='

        self.grid_columnconfigure(0,weight=1)

    def OnButtonClick(self):
        print "you clicked the button!"

    def OnPressEnter(self,event):
        print "you pressed enter!"

if __name__=="__main__":
    app=simpleapp_tk(None)
    app.title('poster')
    app.initialize() # you forgot this
    app.mainloop()

Upvotes: 4

Related Questions