-1

I tried to call press_space() while pressing space key in Text widget but massage error say 'NoneType' object has no attribute 'bind' i used python 2.7

import nltk
root=Tk()
txt=Tkinter.Text(root,font=('arial',30,'bold'),bd=5,           bg="grey",foreground="red",width="31",height="5").grid(columnspan=50,rowspan=30, column=0)
txt.bind('<space>', press_space)

def press_space():
          print ('Hello world')
  • 1
    You need to call `grid` on a new line like `txt.grid(...)` also bind passes an event argument to callback function, so you need to change `def press_space()` to either `def press_space(event)` or `def press_space(*args)`. – Nae Dec 03 '17 at 00:28

1 Answers1

0

Very popular mistake

var = Widget(...).grid()

It assigns to var value returned by grid() - None - so later you get None.bind()

You have to do it in two lines

var = Widget(...)
var.grid()

After that bind() will work correctly.


BTW: bind() executes function with argument event which you have to receive.

import tkinter as tk

# --- functions ---

def press_space(event):
    #print(event)
    #print( dir(event) )
    print('Hello world')

# --- main ---

root = tk.Tk()

txt = tk.Text(root)
txt.grid()

txt.bind('<space>', press_space)

root.mainloop()
furas
  • 134,197
  • 12
  • 106
  • 148